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

如何在Node.js Socket.IO代码中配置CORS解决跨域请求拦截问题

Socket.IO服务CORS跨域配置正确方案

现有代码问题排查

  • 实例化Socket.IO的语法错误:你写的const io = socket(server)(8000, { ... })属于无效调用,引入的socket.io构造函数接收http服务实例作为第一个参数,配置项直接作为第二个参数传入,不需要二次调用传端口。
  • 端口重复绑定:你既在Socket.IO初始化时传入8000端口,又调用server.listen(8000)重复监听端口,会触发运行时错误。

修正后的完整代码

const axios = require('axios');
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const socket = require('socket.io');
// 正确配置CORS规则
const io = socket(server, {
  cors: {
    // 允许的前端来源,单个来源写字符串,多个来源放入数组
    origin: ['http://localhost:3000'],
    // 若前端请求携带Cookie、授权头等凭证信息,需开启该配置
    credentials: true,
    // 允许的请求方法,可根据业务需求调整
    methods: ["GET", "POST"]
  }
});

// 此处保留你原有业务逻辑代码

server.listen(8000, () => console.log('server is running on port 8000'));

补充说明

生产环境不建议将origin设为*(允许所有来源跨域),建议明确指定可信的前端域名列表,避免安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 19:30:02