'How to handle React Router with Node Express routing

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



Solution 1:[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);

Solution 2:[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

Solution 3:[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.

Solution 4:[4]

my router :

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Eran Abir
Solution 3 jxzheng16
Solution 4 Eran Abir