0

http-proxy module doesn't work with create-react-app, but works with serve -s build

This is my proxy-server code.

So what it does - it joins 2 api servers on different ports and frontend to a single 80 port. When you open localhost:80/* it should open react frontend (3000 port). When you open /api it gives you data from 4000 port and /secondapi from 1000 port.

My 2 backend api servers are opening completely fine with it.

Also when I start frontend server using serve module it also works fine and returns my frontend part.

But if I start frontend at the same 3000 port using "npm start" my proxy server returns connect ECONNREFUSED ::1:3000

const httpProxy = require('http-proxy');
const http = require('http');
const { maintenanceHtml } = require('./maintenanceHtml');


const proxy = httpProxy.createServer();

const guiUrl = 'http://localhost:3000'; // react frontend app

const apiUrl = 'http://localhost:4000'; // 1st api server
const apiPrefix = '/api';

const fnApiUrl = 'http://localhost:1000'; // 2nd api server
const fnApiPrefix = '/secondapi';

const port = 80;

http.createServer((req, res) => {
  let target = guiUrl;
  if (req.url.startsWith(apiPrefix)) {
    req.url = req.url.replace(apiPrefix, '/');
    target = apiUrl;
  }
  if (req.url.startsWith(fnApiPrefix)) {
    req.url = req.url.replace(fnApiPrefix, '/');
    target = fnApiUrl;
  }
    proxy.web(req, res, { target })

    proxy.on('error', (error) => {
      console.log(error.message)
      res.end(maintenanceHtml);
    })
}).listen(port, () => {
  console.log(`Proxy server has started on port 80`)
});

I think that there is react server settings that I'm not able to find.

There is a little example that you're able to start at your own PC.

https://github.com/b2b-Alexander/react-js-problem

  • Also i can add that this problem is only on my notebook. I copied project from my main PC to notebook, installed packages and started both my backend and frontend, I have thought that source of the packages could be updated since I installed them on my main PC. So i deleted node_modules on main PC and reinstalled packages. Problem did not appeared on my main PC. – Alexander 2049 Dec 30 '22 at 20:57
  • Does opening `localhost:3000` in the browser work? – Konrad Dec 30 '22 at 20:59
  • Yes, it does opening `localhost:3000` in both cases (`npm start` and `serve -s build`). – Alexander 2049 Dec 30 '22 at 23:11
  • https://github.com/b2b-Alexander/react-js-problem Example project that you can start at your own PC and look at the code. – Alexander 2049 Dec 31 '22 at 13:41

1 Answers1

0

Found solution on github: https://github.com/vitejs/vite/discussions/7620

I got installed new v18.12.1 version of NodeJS.

My main machine has v16.14.0

So I rolled back the version of NodeJS for my project.