Reputation: 2804
I'm not able to figure out how react router and express route working together.
I have this
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
The problem is my api can't use GET because it will redirect to index.html. If I remove the wildcard route, then react-router would not be able to work properly.
Upvotes: 0
Views: 1760
Reputation: 11
Simply change the order of the routes, so that your backend routes are matched first.
Upvotes: 1
Reputation: 20246
Your app.get('*')
statement will match any request coming in. You can fix your problem by changing the order of the statements:
// routes
const apiRoutes = require('./server/routes/api');
app.use('/api', apiRoutes);
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
});
This way, any requests whose path's start with /api
will be handled by your apiRoutes
router, all the others are handled by the asterisk.
Upvotes: 5