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
But if you just remember that React isn't an application, but a set of files, then you'll have no problem integrating Express with React in any way you'd like. One simple way is to use Express's static file server to server files to the browser that contain your React app.
With the combination of Node and React, developers don't require learning complex back-end languages like Python or Ruby. They can use Node for server-side development and React for front-end code building without switching between frameworks and programming languages. And it saves resources, money, and time.
Currently React Client and Express server work independently on ports 8081 and 8080 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With