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

React应用连接Socket.io服务器请求被拦截:本地正常VPS异常

React连接Socket.io VPS环境请求拦截问题排查方案

核心现象

本地环境React应用可正常连接Socket.io服务器,但部署到VPS后请求被拦截;直接访问http://server_ip:8007/socket.io/?EIO=4&transport=polling能返回有效响应:0{"sid":"VaHqLXI5UVRRaeUAAAAV","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}


1. 检查VPS防火墙/安全组规则

直接访问polling链接正常,但Socket.io会尝试升级到WebSocket协议,部分防火墙会拦截ws/wss流量:

  • 确认VPS安全组已开放8007端口的TCP入站流量(WebSocket基于TCP,无需额外端口);
  • 若使用iptables,添加放行规则:
    iptables -A INPUT -p tcp --dport 8007 -j ACCEPT
    

2. 修正前端Socket.io连接配置

本地部署和VPS部署的连接地址、协议配置差异会导致失败:

  • 替换硬编码的localhost为VPS公网IP/域名,同时明确指定传输方式:
    import { io } from "socket.io-client";
    const socket = io("http://你的VPS公网IP:8007", {
      transports: ["polling", "websocket"], // 优先用polling完成握手,再升级WebSocket
      withCredentials: true // 若服务器开启跨域凭证验证,需开启此项
    });
    
  • 确保客户端与服务器的Socket.io主版本一致(如均为4.x系列),版本不兼容会导致握手失败。

3. 配置Nginx反向代理的WebSocket支持(若使用Nginx)

若VPS用Nginx做反向代理,未配置WebSocket转发规则会导致升级请求被拦截:

  • 在Nginx的server块中添加如下配置:
    location /socket.io/ {
        proxy_pass http://localhost:8007;
        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;
    }
    
  • 重启Nginx生效:
    sudo systemctl restart nginx
    

4. 完善服务器端CORS配置

浏览器的CORS预检机制可能拦截前端请求,需在Socket.io服务器端配置允许的前端来源:

const { Server } = require("socket.io");
const io = new Server(8007, {
  cors: {
    origin: "http://你的前端域名/IP", // 生产环境建议指定具体域名,测试可用"*"
    methods: ["GET", "POST"],
    credentials: true
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:35:25