0
votes

I'm trying to run an Express server and React app together. When I use npm run server it starts the react server instead of the express server. If I go to the localhost for the express server ("http://localhost:3001/api/greeting") I get a message saying "This site can’t be reached".

I set up my server with these instructions: https://www.twilio.com/blog/react-app-with-node-js-server-proxy

It fails when I test the server I've created.

server/index.js

const express = require('express');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

app.listen(3001, () =>
  console.log('Express server is running on localhost:3001')
);

package.json

"devDependencies": {
    "body-parser": "^1.19.0",
    "create-cep-extension-scripts": "1.0.0-beta.29",
    "express": "^4.17.1",
    "express-pino-logger": "^4.0.0",
    "node-env-run": "^3.0.2",
    "nodemon": "^1.19.1",
    "npm-run-all": "^4.1.5",
    "pino-colada": "^1.4.5"
  },
  "scripts": {
    "start": "create-cep-extension-scripts start",
    "build": "create-cep-extension-scripts build",
    "test": "create-cep-extension-scripts test --env=jsdom",
    "eject": "create-cep-extension-scripts eject",
    "archive": "create-cep-extension-scripts archive",
    "server": "node-env-run server --exec nodemon | pino-colada"
  }

npm run server is supposed to start my express server and display a JSON response with a "Hello World!" greeting. Instead I'm getting a page with a message "This site can’t be reached."

1
do you at least see Express server is running on localhost:3001 in your terminal - WilomGfx
No, it's not logging anything - sbaden
Under the "This site can't be reached" There is an error: ERR_CONNECTION_REFUSED - sbaden
well of course, if it does not even start the server, you wont be able to connect :P. Make sure you configured everything correctly. you might need some variables in a .env file to be used by node-env-run. - WilomGfx
The article I was following says to create the .env file but it never said what to put in it. - sbaden

1 Answers

0
votes

Are you sure you ran npm install before doing anything? Your package.json file seems to miss one outer curly bracket. I think your npm run server command does not run because your project is missing the dependencies like node-env-run, pina-colada or nodemon. Also, you should add an empty .env file in the top level of your project.