Skip to content
Advertisement

react router and express GET conflict

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement