部署到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
相关产品推荐
相关产品推荐

