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

Node+Express+Socket.io持续轮询异常求助:频繁触发Polling GET请求

Fixing Persistent Polling in Node+Express+Socket.io

Hey there! Let’s tackle why your Socket.io setup is stuck on continuous polling instead of using WebSocket like it should. Here’s what to check and fix:

1. Remove Extra Spaces in Client Connection URL

First, look at your client code:

socket = io.connect(' http://localhost:8890 ')

The spaces around the URL are causing a parsing issue—Socket.io can’t properly negotiate the WebSocket handshake with that malformed URL. Fix it by trimming the spaces:

socket = io.connect('http://localhost:8890')

This is the most likely culprit here, so start with this fix!

2. Verify Socket.io Initialization & CORS Settings

Your server code looks correct (using http.Server to wrap Express before passing to Socket.io), but if your client runs on a different port/domain later, you’ll need to configure CORS explicitly to avoid handshake failures:

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server, {
  cors: {
    origin: "http://your-client-origin:port", // e.g., "http://localhost:3000"
    methods: ["GET", "POST"]
  }
});
server.listen(8890);

io.on('connection', function (socket) {
  console.log(socket['id'] + " client connected");
});

For local localhost development, CORS usually isn’t an issue, but it’s good to keep this in mind if you expand your setup.

3. Check for Version Mismatches

Make sure your client-side Socket.io version matches the server-side one. If there’s a major version gap (e.g., server uses v4, client uses v2), the handshake will fail, and Socket.io will fall back to polling indefinitely.

  • Check server version: Look at package.json for the socket.io version
  • Match client version: If using a CDN, use the corresponding version (e.g., for v4.7.2: <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>)

4. Debug with Browser Dev Tools

Open your browser’s developer tools (F12) and check:

  • Console tab: Look for errors related to WebSocket connections (e.g., 404 errors, CORS blocks)
  • Network tab: Filter by "WS" to see if a WebSocket connection attempt was made and failed. If you only see polling requests, that confirms the handshake never succeeded.

After making these changes, your Socket.io should switch to WebSocket once the handshake works, and the polling requests will stop.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:39:41