Socket.IO持续出现轮询404错误(Socket.IO新手求助)
问题解决:Socket.IO 404错误修复
核心问题
你在app.ts中创建了绑定Socket.IO的httpServer,但在index.ts里又重新创建了一个全新的HTTP服务器,导致Socket.IO的路由没有挂载到实际运行的服务器上,客户端请求/socket.io/路径时自然返回404。
修复步骤
1. 修改app.ts,导出绑定Socket.IO的HTTP服务器
将app.ts中的httpServer导出,供index.ts使用:
import express from 'express'; import morgan from 'morgan'; import favicon from 'serve-favicon'; import path from 'path'; import cors from 'cors'; import { errorManager } from './middlewares/errors_middleware.js'; import { ordersRouter } from './routers/OrdersRouter.js'; import { usersRouter } from './routers/UsersRouter.js'; import { createServer } from 'http'; import { Server } from 'socket.io'; export const app = express(); export const httpServer = createServer(app); // 导出绑定Socket.IO的服务器实例 const io = new Server(httpServer, { cors: { origin: '*', }, }); io.on('connection', (socket) => { console.log('HELLO'); }); app.use(favicon(path.join('.', 'public', 'favicon.ico'))); app.use(cors()); app.use(morgan('dev')); app.use(express.json()); app.get('/', (_req, res, next) => { res.send('H'); next(); }); // Routers app.use('/orders', ordersRouter); app.use('/users', usersRouter); app.use(errorManager);
2. 修改index.ts,使用绑定Socket.IO的服务器
不再重新创建HTTP服务器,直接使用app.ts导出的httpServer:
import createDebug from 'debug'; import { httpServer } from './app.js'; // 导入绑定Socket.IO的服务器 import { dbConnect } from './dbconnect/dbconnect.js'; const debug = createDebug('StoryLine:INDEX'); const port = 3300; httpServer.on('listening', () => { const addr = httpServer.address(); if (addr === null) return; let bind: string; if (typeof addr === 'string') { bind = 'pipe ' + addr; } else { bind = addr.address === '::' ? `http://localhost:${addr?.port}` : `port ${addr?.port}`; } debug(`SERVER: Listening on: ${bind}`); }); httpServer.on('error', (error: Error) => { debug(`Server error: ${error.message}`); }); dbConnect() .then((mongoose) => { debug( 'Database connection -> SUCCESSFUL: ', mongoose.connection.db.databaseName ); httpServer.listen(port); // 启动绑定Socket.IO的服务器 }) .catch((error) => { debug('Database connection -> COULD NOT CONNECT'); httpServer.emit('error', error); });
3. 客户端连接验证
确保客户端代码正确连接到服务器:
// 客户端示例代码 import { io } from "socket.io-client"; const socket = io("http://localhost:3300"); socket.on("connect", () => { console.log('已连接到服务器'); });
额外修正点
- 移除
index.ts中多余的http模块导入 - 修正
index.ts中error事件回调的参数错误(原回调错误接收response对象,HTTP服务器的error事件不会传递该参数)
内容的提问来源于stack exchange,提问作者Miguel Garcia
相关产品推荐
相关产品推荐

