如何使用Node Express路由处理React Router [英] How to handle React Router with Node Express routing

查看:35
本文介绍了如何使用Node Express路由处理React Router的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用React路由器和Node JS服务器来管理React应用

I am trying to manage a react app with react router and node js server

我的路由器在反应:

        <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}}}/>)

    }/>
   )

};

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

and my router in my NodeJS Server :

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)
});

尝试访问localhost:5000/user时,应用程序运行正常但是当我想访问localhost:5000/api时,它将再次重定向到react应用无法弄清楚如何解决我需要改变什么?谢谢

when trying to access localhost:5000/user react app is working fine but when I want to access localhost:5000/api its redirected to the react app again cannot figure out how to fix it what do I need to change? thanks

推荐答案

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

You need to define Express routes and controllers to match the front-end request.

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

This is most likely invalid/not configured properly: app.use('/api',router);

除非您粘贴 router 文件的外观,否则无法肯定知道.

Impossible to know for sure unless you paste what your router file looks like.

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

Try replacing it with the matching front-end request:

app.delete('/api', callbackfunction)
app.get('/api', callbackfunction)
app.put('/api', callbackfunction)
app.post('/api', callbackfunction)

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

Express needs a request (app.[request]), a route ('/api'), and a controller function (callback function).

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);

这篇关于如何使用Node Express路由处理React Router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆