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

AWS EC2+NGINX环境下Node.js Socket.IO WebSocket遇400错误求助

解决Socket.IO WebSocket 400 Bad Request错误的方案

1. 修正Nginx反向代理配置

REST API正常说明基础反向代理配置有效,但WebSocket需要额外的头部和协议升级支持。修改你的Nginx配置文件(通常位于/etc/nginx/sites-available/或/etc/nginx/nginx.conf),针对Socket.IO的请求路径添加专属配置:

server {
    listen 443 ssl;
    server_name abcdDomain.com;

    # 保留已有的SSL证书配置
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;

    # 保留已有的REST API反向代理配置
    location / {
        proxy_pass http://localhost:3001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 专门处理Socket.IO的WebSocket连接
    location /socket.io/ {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        # 延长超时时间避免连接过早断开
        proxy_connect_timeout 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}

修改后重启Nginx生效:

sudo systemctl restart nginx

2. 优化Socket.IO服务端配置

你的服务端代码基础逻辑没问题,可补充以下参数提升兼容性:

const app = express();
const { createServer } = require("http");
const { Server } = require("socket.io");

const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: ['https://abcdDomain.com', 'http://localhost:3000'],
    methods: ["GET", "POST"],
    credentials: true
  },
  path: "/socket.io/", // 明确指定路径,与Nginx配置匹配
  transports: ["websocket", "polling"] // 优先使用WebSocket传输
});

io.on("connection", (socket) => {
  console.log("Socket connected:", socket.id);
});

httpServer.listen(3001, () => {
  console.log("HTTP server running on port 3001");
});

3. 客户端连接配置调整

确保客户端使用HTTPS域名连接,并匹配服务端指定的路径:

// 客户端代码示例
import { io } from "socket.io-client";

const socket = io("https://abcdDomain.com", {
  path: "/socket.io/",
  transports: ["websocket"], // 可选:强制优先使用WebSocket
  withCredentials: true
});

socket.on("connect", () => {
  console.log("Client connected to socket server");
});

4. 额外检查项

  • 确认EC2安全组已允许入站的443端口(WebSocket通过HTTPS端口传输)
  • 检查Node.js服务是否正常运行在3001端口:sudo lsof -i :3001
  • 查看Nginx错误日志排查细节:sudo tail -f /var/log/nginx/error.log

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:52:38