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

Node.js + Socket.io跨域请求(CORS)错误问题求助

Fixing Socket.io CORS Error in Your Node.js App

Hey there! Let's sort out that CORS error you're hitting with your Socket.io setup. The root issue here is that your Socket.io module's init function isn't actually using the CORS configuration you're passing when you call it. Let's break this down and fix it step by step.

The Problem

When you call init(server, { cors: { origin: "*", methods: ["GET", "POST"] } }), your init function only accepts the httpServer parameter and ignores the second options argument. That means your CORS settings never get applied to Socket.io—so it's using the default restrictive CORS rules, which triggers your error.

The Fix

Update your Socket.io module to accept and pass along the options parameter to the Socket.io constructor:

let io;
module.exports = {
    // Add the `options` parameter to the init function
    init: (httpServer, options) => {
        // Pass both the server and options to socket.io
        io = require("socket.io")(httpServer, options);
        return io;
    },
    getIO: () => {
        if (!io) {
            throw new Error("Socket.io not initialized");
        }
        return io;
    },
};

Your existing call to init is already correct, so once you update the module, the CORS configuration will take effect properly:

const io = require("./socket").init(server, { 
    cors: { 
        origin: "*", 
        methods: ["GET", "POST"], 
    }, 
});

Quick Production Safety Tip

While origin: "*" works fine for development, it's not secure for production. Instead, specify the exact frontend domains that need access to your Socket.io server, like:

cors: { 
    origin: "https://your-production-frontend.com", 
    methods: ["GET", "POST"], 
    credentials: true // Include this if you need to send cookies or auth headers
}

That should resolve your CORS error and let your Socket.io connection work smoothly across domains!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:54:06