This might be marked as a duplicate but I looked at all the Stack Overflow posts on this topic. I also listed some of them below. Many of the posts on this topic also didn't have a correct answer "ticked".
I have a React app that I wish to connect to a Node server using Express. It is the first time I do this so I followed this post https://www.twilio.com/blog/react-app-with-node-js-server-proxy. I followed all the instructions, as far as I can see, I have checked several times. So I went and did research to see if I can figure out what the problem is.
When I run npm run dev
to start up both the sever and the React app, the React app shows correctly in my browser. However when I type my name in the textbox I get the following error in my terminal:
[HPM] Error occurred while trying to proxy request /api/greeting?name=Johnnie from localhost:3000 to http://localhost:3001/ (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
In my console on the front-end I get:
VM92:1 GET http://localhost:3000/api/greeting?name=Johnnie 504 (Gateway Timeout)
Uncaught (in promise) SyntaxError: Unexpected token E in JSON at position 0
Fetch failed loading: GET "http://localhost:3000/api/greeting?name=Johnnie.
I did hours of research and followed some instructions on the following StackOverflow posts:
React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
fetch gives response Unexpected token < in JSON
……and more
I added a setupProxy.js file too.
Here is my package .json snippet:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"server": "node-env-run server --exec nodemon | pino-colada",
"dev": "run-p server start"
},
"proxy": "https://localhost:3001/",
My .env
REACT_APP_API_URL=http://localhost:3001
setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(createProxyMiddleware("/api/*", { target: "http://localhost:3001/" }));
};
server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const pino = require('express-pino-logger')();
const PORT = 3001;
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')
);
The handleSubmit function in App.js
handleSubmit(event) {
event.preventDefault();
fetch(`/api/greeting?name=${encodeURIComponent(this.state.name)}`)
.then(response => response.json())
.then(state => this.setState(state));
}
I know the issue has to do with the server and app not running concurrently but I don't know what could be wrong.