0

I want to serve my react front-end on localhost:5000, and the api requests will go to localhost:5000/api/some-path.

I have seen some similar questions and from what I have understood :

  • Add proxy in package.json

  • Serve static files from build folder

relevant part of package.json:

  "proxy" : "http://localhost:5000",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Relevant part of server.js :

const PORT = 5000 || process.env.port;
app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function(req,res) {
  res.sendFile(path.join(__dirname, '../public', 'index.html'));
});

Commands for production :

$ npm run build
$ serve -s build

The issue is that, each fetch request's response is the index.html file.

Note that, in the dev build everything was working fine. I was starting react app from port 3000 and requests were going to localhost:5000/api/path responding with json data.

2 Answers 2

1

The problem was with this line : app.use(express.static(path.join(__dirname, 'build'))); The build folder was outside the folder which contains the file server.js. Corrected to : app.use(express.static(path.join(__dirname, '../build')));

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

Comments

0

As someone new to code, I've recently had a hard time deploying react and node. How I ended up doing it was:

  1. Build the react app with npm run build
  2. Copy the build folder in the root of the node.js project
  3. Include this code in the index or app.js
app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function(req,res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

const PORT = 5000 || process.env.port;
app.listen(PORT, ()=> console.log(`Listening on port ${PORT}...`));
  1. Start the app with node index.js or node app.js and that's it

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.