How to handle React Router with Node Express routing

时间秒杀一切 提交于 2021-02-10 04:12:24

问题


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

my router in react :

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

    }/>
   )

};

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

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


回答1:


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

This is most likely invalid/not configured properly: app.use('/api',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 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);



回答2:


Solved !

because i created the react app with create-react-app cli i needed to add to package.json file this line :

"proxy": "http://localhost:5000"

and now when i am trying to make a GET request like that :

axios.get('/api/someurl') is working as expected

thank you all




回答3:


What does your express route look like? Like the above user said, it really depends on what your router file looks like on the line

app.use('/api', router);

There is no need to define your API routes in react-router. However, I think you're misunderstanding how they work together. Usually react-router is used for client side routing while express handles your backend routes such as fetching data. You use react router to route users to different pages and views while your express routes would just render data.




回答4:


my router :

const router = express.Router({});
router.get('/someurl',(res,req)=>{
       res.status(201).json({ message: "Hello World!" })
});


来源:https://stackoverflow.com/questions/52334591/how-to-handle-react-router-with-node-express-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!