Node.js + Socket.io跨域请求(CORS)错误问题求助
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

