Lalas M
Lalas M

Reputation: 1174

How to resolve 'cannot GET' error on react routes when using ExpressJS to serve react build?

I have the following folder structure for a React client and ExpressJS server setup. I'm trying to serve the react build files from the Express server. I also have defined some route handlers for API from the express server

server                    /* NodeJS server folder
  -node_modules
  -app.js
  -package.json
client                    /* React client folder  
  -build
  -node_modules
  -src
     -components
     -App.js
     -index.js
  -package.json

My express (app.js) has the following code

app.use(express.static(path.join(__dirname, '../client/build')));
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, '../client/build', 'index.html'));
});
...
...
app.get('/data', (req, res) => {
    res.json(data);
});

Here I'm able to see the home page of my React application but all the routes throws Cannot GET /reactroute. I'm also able to access the /data as defined by app.get handler

Referring some other answers I changed my code in the express server as

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../client/build', 'index.html'));
});
...
...
app.get('/data', (req, res) => {
    res.json(data);
});

At this time I'm able to access the routes from the react but the /data is not giving the JSON (API) instead it is acting like an another route. What changes need to be done to get both react routes from the build folder and the route handlers defined in the express.

Upvotes: 0

Views: 722

Answers (1)

Mani
Mani

Reputation: 290

You have to place get /data before get *. Like this:

app.get('/data', (req, res) => {
    res.json(data);
});
...
...
app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, '../client/build', 'index.html'));
});

If you place get * first, it also includes /data. Where * considers all routes which are not mentioned before it.

Upvotes: 1

Related Questions