I’m not able to figure out how react router and express route working together.
I have this
JavaScript
x
8
1
app.get('*', function(req, res) {
2
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
3
});
4
5
// routes
6
const apiRoutes = require('./server/routes/api');
7
app.use('/api', apiRoutes);
8
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.
Advertisement
Answer
Your app.get('*')
statement will match any request coming in. You can fix your problem by changing the order of the statements:
JavaScript
1
8
1
// routes
2
const apiRoutes = require('./server/routes/api');
3
app.use('/api', apiRoutes);
4
5
app.get('*', function(req, res) {
6
res.sendFile(path.resolve(__dirname) + '/server/static/index.html');
7
});
8
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.