Socket.io服务器无法与Angular正常连接,请求技术支持
Express + Socket.io 跨域连接问题解决
问题场景
我在Express服务器中尝试实现Socket.io,前端通过Angular服务连接时出现了CORS相关错误及404问题,相关代码如下:
App类代码
app: Application; server: http.Server | https.Server; sockets: SocketIo; constructor() { this.app = express(); this.app.use(cors()); this.server = http.createServer(this.app); this.iniciarSockets(); this.server.listen(3000, () => .....) } private async iniciarSockets() { this.sockets = new SocketIo(this.server); }
SocketIo类代码
import http from 'http'; import https from 'https'; import { Server, Socket } from 'socket.io'; export class SocketIo { io: Server; constructor(server: http.Server | https.Server) { this.io = require("socket.io")(server); this.io.on("connection", (socket: Socket) => { console.log("New connection"); socket.emit("test event", "Here is some data"); }) } }
Angular服务代码
export class WebSocketService { socket: any; readonly url: string = "ws://localhost:3000"; constructor() { this.socket = io(this.url); } listen(eventName: string) { return new Observable((subscriber) => { this.socket.on(eventName, (data) => { subscriber.next(data); }) }) } emit(eventName: string, data: any) { this.socket.emit(eventName, data); } }
遇到的错误
控制台出现三个错误:
zone.js:2707 GET http://localhost:4200/socket.io/?EIO=4&transport=polling&t=OXzMsOL 404 (Not Found)Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OXzMsOR' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OXzMsOR net::ERR_FAILED 200 (OK)
解决步骤
1. 配置Socket.io专属CORS规则
Express的cors()中间件仅处理普通HTTP请求,Socket.io有独立的CORS配置项,需在初始化时明确指定:
修改SocketIo类的构造函数:
constructor(server: http.Server | https.Server) { // 改用ES模块方式初始化Server,替代require this.io = new Server(server, { cors: { origin: "http://localhost:4200", // 允许连接的前端域名 methods: ["GET", "POST"] } }); this.io.on("connection", (socket: Socket) => { console.log("New connection"); socket.emit("test event", "Here is some data"); }); }
2. 修正Angular客户端连接地址
Socket.io客户端默认会通过HTTP协议完成握手,无需指定ws://协议头,直接使用HTTP地址即可:
修改Angular服务的url:
readonly url: string = "http://localhost:3000";
3. 确保服务端依赖导入规范
移除require("socket.io")的用法,保持与顶部import { Server } from 'socket.io'的ES模块导入一致,避免混合导入导致的异常。
4. 对齐客户端与服务端版本
确保socket.io(服务端)和socket.io-client(Angular客户端)版本一致,避免版本不兼容导致的握手失败:
# 服务端安装最新版 npm install socket.io@latest # Angular客户端安装对应版本 npm install socket.io-client@latest
内容的提问来源于stack exchange,提问作者Franco Mendoza
相关产品推荐
相关产品推荐

