You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署到Ubuntu(Nginx+Node.js+React)后Socket.io无法连接问题

修复步骤

1. 调整Nginx配置

删除配置中多余的location ~* \.io块,修改/api路由配置如下:

server {
  listen 80;

  location / {
        root /var/www/bacotin/client;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
  }

  location /api {
        proxy_pass http://localhost:3000/;
        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;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

修改完成后执行sudo systemctl restart nginx重启Nginx生效。

2. 修改服务端Socket.io初始化配置

补充跨域配置和路径匹配规则:

const server = app.listen(3000, 'localhost');
const io = socketio(server, {
  cors: {
    origin: "http://103.150.60.132", // 生产环境不要用*,指定前端域名即可
    methods: ["GET", "POST"],
    credentials: true
  },
  path: "/api/socket.io"
});

3. 修改客户端Socket连接配置

调整连接参数和服务端配置对应:

const socket = io("http://103.150.60.132", {
  path: "/api/socket.io"
});

4. 辅助检查项

  • 确认VPS防火墙开放80端口:执行sudo ufw allow 80/tcp添加规则
  • 重启Express后端服务后再测试连接

内容的提问来源于stack exchange,提问作者Zulfikar Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:54:08