Hannes Skoog
Hannes Skoog

Reputation: 45

Express server isn't running on my React production build

I have a React app made with create-react-app which I am trying to run on an express server. It works fine when running npm start but when running npm run build and then serve -g build I can only connect to port 5000 on localhost and not 8080 which I set up in the express server.

server.js

const express = require('express');
const jsonServer = require('json-server')
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));

app.get('/ping', function (req, res) {
 return res.send('pong');
});

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

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

app.use('/api', jsonServer.router('./src/config.json'));

app.listen(process.env.PORT || 8080);

I have also setup my proxy and main

package.json

"main": "server.js",
"proxy": "http://localhost:8080",

How can I make this work?

Upvotes: 2

Views: 3974

Answers (1)

Mocca
Mocca

Reputation: 499

As you correctly said, proxy directive works well in development mode, with npm start.

Also, as you correctly said, serve -g build command, serves correctly your production build in localhost:5000.

For your main purpose, that is to serve your production build within your express server, you need to generate the production build with:

npm run build

And then serve it in one of your server endpoints, as follows:

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

And don't forget to start your server with

node server.js

Upvotes: 2

Related Questions