Proxy between React and Node app is not working

Viewed 115

I'm building a React/Express app, where HTTP requests from the client are passed via a proxy to the express app. I've set up my server at port 5000, and set up a proxy to this in my client-side package-json file. I'm also using the npm package Concurrently to simultaneously run both the react and node server. The proxy is however failing and I'm getting the following error in my terminal upon npm start:

Proxy error: Could not proxy request /hello from localhost:3000 to http://localhost:5000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

I've tried deleting the client-side node modules and package-lock.json, in roder to clear the cache, but this hasn't worked. Any suggestions?

I've also noticed int he broswer that requests are being made to localhost:3000, instead of localhost:5000:

Failed to load resource: the server responded with a status of 500 (Internal Server Error):3000/hello:1 
500 (Internal Server Error)

Server set up:

server/index.json

const express = require('express')

const port = process.env.PORT || 5000

const app = express()

app.get('/hello', (req,res) => {
    res.send({message: 'hello from server'})
})


app.listen(port, () => {
    console.log(`️ Server listening on port ${port}`)
})

Client-side package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000/",
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },

Server-side package.json:

{
  "name": "react-node-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "server": "nodemon index.js --ignore client",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "concurrently": "^6.3.0"
  }
}

App.js:

import { useState, useEffect } from 'react'
import logo from './logo.svg';
import './App.css';

const App = () => {

const [ data, setData ] = useState(null)

useEffect(() => {
  fetch('/hello')
  .then(res => res.json)
  .then(data => setData(data.message))
},[])

  return (
    <div>
      <p>
        {
          data
        }
      </p>
    </div>
  )
}

export default App;

0 Answers
Related