如何使用 Node Express 路由处理 React Router

Era*_*bir 5 node.js express reactjs react-router

我正在尝试使用反应路由器和节点 js 服务器管理反应应用程序

我的路由器反应:

        <BrowserRouter>
        <Switch>
            <PrivateRoute token={token} Component={Payments} exact path="/payments"/>
            <PrivateRoute token={token} Component={User} exact path="/user"/>
            <PrivateRoute token={token} Component={User} exact path=""/>
            <PrivateRoute token={token} Component={User} exact path="/"/>
        </Switch>
       <BrowserRouter/>

 export const PrivateRoute = ({Component, ...rest,token}) => {

   return (
    <Route {...rest} render={props => token ? (<Component {...props}/>) :
        (<Redirect to={{pathname: '/login', state: {from: props.location}}}/>)

    }/>
   )

};
Run Code Online (Sandbox Code Playgroud)

和我的 NodeJS 服务器中的路由器:

const app = express();
const server = new Server(app);
const port = process.env.PORT || 5000;
app.use('/api',router);
app.use(express.static(path.join(__dirname, '/../react_dist')));
app.use('*',  (req, res)=> {
 res.sendFile(path.join(__dirname, '/../react_dist', 'index.html'));
});
server.listen(port,()=>{
 console.log('Server Is up : ', port)
});
Run Code Online (Sandbox Code Playgroud)

当尝试访问 localhost:5000/user react 应用程序工作正常但是当我想访问 localhost:5000/api 时它再次重定向到 react 应用程序无法弄清楚如何修复它我需要更改什么?谢谢

Mat*_*tta 11

您需要定义 Express 路由和控制器以匹配前端请求。

这很可能无效/未正确配置: app.use('/api',router);

除非您粘贴router文件的外观,否则无法确定。

尝试用匹配的前端请求替换它:

app.delete('/api', callbackfunction)
app.get('/api', callbackfunction)
app.put('/api', callbackfunction)
app.post('/api', callbackfunction)
Run Code Online (Sandbox Code Playgroud)

Express 需要一个请求(app.[request])、一个路由('/api')和一个控制器函数(回调函数)。

app.get('/api', (req, res, done) => res.status(201).json({ message: "Hello World!" }));

app.use(express.static('client/build'));

app.get('*', (req, res) => res.sendFile(path.resolve('client', 'build', 'index.html')));

app.listen(5000);
Run Code Online (Sandbox Code Playgroud)


Era*_*bir 7

解决了 !

因为我使用 create-react-app cli 创建了 React 应用程序,所以我需要将这一行添加到 package.json 文件中:

“代理”:“ http://localhost:5000

现在当我尝试发出这样的 GET 请求时:

axios.get('/api/someurl') 正在按预期工作

谢谢你们