简体   繁体   English

部署到 ubuntu 后套接字 io 未连接(nginx、nodejs、reactjs)

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

I have MERN app, the api build with express and the client build with reactjs.我有 MERN 应用程序,使用 express 构建 api,使用 reactjs 构建客户端。

In my local computer (windows), the client can connect to socket server.在我的本地计算机(Windows)中,客户端可以连接到套接字服务器。 The onConnection event is triggered. onConnection 事件被触发。

1. Local Computer (Windows) 1. 本地计算机 (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) 2. VPS (Ubuntu 20, Nginx)

When i deploy the server and the client to vps, the socket can't connect.当我将服务器和客户端部署到 vps 时,套接字无法连接。 on connection event not triggered.未触发连接事件

But the client is trigger connect_error event:但是客户端是触发connect_error事件:

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: NGINX 配置:

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";
    }


}

UPDATE: the problem is solve, now the socket client can connect to the socket server.更新:问题解决了,现在socket客户端可以连接到socket服务器了。

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?但为什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM