Socket io not connected after deploy to ubuntu (nginx, nodejs, reactjs)

Viewed 232

I have MERN app, the api build with express and the client build with reactjs.

In my local computer (windows), the client can connect to socket server. The onConnection event is triggered.

1. Local Computer (Windows)

Client Side:

socket.on('connect', () => {
     console.log('connected to the socket server');
}) // triggered and i can see the console.log in broser console

Server Side:

io.on('connection', () => {
     console.log('client connected to the socket server');
}) // triggered and i can see the console.log in terminal

2. VPS (Ubuntu 20, Nginx)

When i deploy the server and the client to vps, the socket can't connect. on connection event not triggered.

But the client is trigger connect_error event:

socket.on("connect_error", (error) => {
   console.log('socket connection error:', error.message) // socket connection error: server error
}); // this event is triggered

This is my code:

Server side:

const server = app.listen(3000)
const io = socketio(server)

Client side:

const socket = io("http://103.150.60.132/api")

NGINX Config:

server {
  listen 80;

  location / {
        root /var/www/bacotin/client; //reactjs build location
        index  index.html index.htm;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        try_files $uri $uri/ /index.html;
  }

  location /api {
        proxy_pass http://103.150.60.132:3000; // express api
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
  }

 
  location ~* \.io {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy false;

      proxy_pass http://localhost:3000;
      proxy_redirect off;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }


}
1 Answers

UPDATE: the problem is solve, now the socket client can connect to the socket server.

Just modify the client code:

From this:

const socket = io("http://103.150.60.132/api")

To this:

const socket = io("http://103.150.60.132")

But why?

Related