Jenny Mok
Jenny Mok

Reputation: 2804

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.

Upvotes: 0

Views: 1760

Answers (2)

Aman Kushwaha
Aman Kushwaha

Reputation: 11

Simply change the order of the routes, so that your backend routes are matched first.

Upvotes: 1

Patrick Hund
Patrick Hund

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

Related Questions