Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket IO with React and Express. ReactJS Error: Could not proxy request /socket.io/?EIO=4..... from localhost:3000 to http://127.0.0.1:4000

I am trying to establish a connection between my creat-react-app frontend with my express backend. I set up the proxy to the port in which my backend serves on (4000). When I run the app, a proxy error occurs on the frontend:

Proxy error: Could not proxy request /socket.io/?EIO=4&transport=polling&t=NRRFdVj&sid=CJzhACsXDlXmP4aRAAAQ from localhost:3000 to http://127.0.0.1:4000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

Here is my code:

backend/index.js

const app = require('express')();
const http = require('http');
const server = http.createServer(app);

const io = require('socket.io')(server);

io.on('connection', (socket) => {
  console.log('New WS connection....');
});

server.listen(4000, () => console.log('Server running on port 4000'));

frontend/App.js

import React from 'react';
import socketClient from 'socket.io-client';

const App = () => {
  const socket = socketClient();
  return <div>hello</div>;
};

export default App;

frontend/package.json

{
  "name": "frontend",
  "proxy": "http://127.0.0.1:4000/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.8",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.6.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "socket.io-client": "^3.0.5",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

The proxy works fine when I fetch data from the backend, but just when using it in this case a proxy error occurs...

like image 614
Aidenhsy Avatar asked Aug 02 '26 10:08

Aidenhsy


1 Answers

Try the below code. You didn't add the URL argument on socketClient([URL][,options]);

import React from 'react';
import socketClient from 'socket.io-client';

const App = () => {
  const socket = socketClient("http://localhost:4000");
  return <div>hello</div>;
};

export default App;
like image 67
Mike B. Avatar answered Aug 05 '26 07:08

Mike B.