0

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.

6
  • You have to place get /data before get *. If you place get * first, it also includes /data. Commented Nov 12, 2021 at 7:49
  • Can you post your full server/app.js file? Commented Nov 12, 2021 at 7:50
  • @Mani I think your solution works here thanks. If you can post it as an answer by reasoning it will be helpful for other Commented Nov 12, 2021 at 8:07
  • Okay, I will answer with explanation Commented Nov 12, 2021 at 8:08
  • @LucaPizzini thanks for your response. I do not have much in the app.js as I'm doing some learning and testing .. Commented Nov 12, 2021 at 8:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.