Socket.io 2.1.0请求出现404错误,寻求非降级解决方案
Fixing Socket.io 2.1.0 404 Polling Error (No Downgrade Needed)
Let's jump straight to fixing your issue—no need to roll back versions. The 404 error you're seeing stems from two easy-to-fix gaps in your setup.
Why the Error Happens
Your request is hitting http://localhost/socket.io/ instead of the correct http://localhost:3000/socket.io/ because:
- Your server isn't actually running on port 3000—you forgot to start the HTTP listener, so Socket.io's endpoint doesn't exist at that port.
- The client connection code has a redundant call that can lead to unintended default behavior.
Step 1: Fix the Server Code
This is the most critical change. Add the missing port listener to your server.js to launch your Express and Socket.io services on 3000:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); // Add this line to start listening on port 3000 http.listen(3000, function(){ console.log('listening on *:3000'); });
Step 2: Simplify the Client Connection
Socket.io 2.x doesn't require combining io() and connect()—simplify your client code to explicitly target the correct server URL, eliminating any ambiguity:
<script src="http://localhost:3000/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <script> $(function () { // Directly specify the server URL for clear, reliable connection var socket = io('http://localhost:3000'); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); }); </script>
Final Quick Checks
- Access your app via
http://localhost:3000(don't openindex.htmldirectly with thefile://protocol—this causes cross-origin issues). - Restart your server after making changes, then refresh the client page.
This should resolve the 404 error completely while keeping you on Socket.io 2.1.0.
内容的提问来源于stack exchange,提问作者User
相关产品推荐
相关产品推荐

