Node.js+React项目中Socket.IO跨域问题:No 'Access-Control-Allow-Origin' 错误排查求助
Looks like the issue lies in how you're configuring CORS for your Socket.IO server. Starting from Socket.IO v3, the library updated its CORS handling mechanism, and your current approach using origins and a custom handlePreflightRequest isn’t the recommended (or functional) method anymore.
Here’s the corrected backend code that should resolve the CORS error:
const express = require('express'); const app = express(); const server = app.listen(1337); const io = require('socket.io')(server, { cors: { origin: "http://localhost:3000", // Allow your React app's origin methods: ["GET", "POST"], allowedHeaders: ["my-custom-header"], credentials: true } }); io.on('connection', (socket) => { console.log('connected'); socket.on('message', (message) => { console.log('message received:', message); }); socket.emit('message', 'toto'); });
Why this fixes the problem:
Socket.IO now includes a dedicated cors configuration option that automatically handles all preflight requests. Your old code tried to manually manage preflight responses, but Socket.IO’s built-in CORS handling ensures the correct Access-Control-Allow-Origin (and other required) headers are sent with every request—including the polling requests mentioned in your error log.
Frontend check:
Your React code is already set up correctly (the withCredentials: true matches the server’s credential allowance). Just make sure your Socket.IO client version matches the server version (e.g., both are v4.x) — version mismatches can sometimes trigger unexpected CORS-like issues.
If you still run into trouble, double-check:
- That your backend is actually running on port 1337
- No browser extensions (like ad blockers or CORS testers) are interfering with the request
- Your React app is indeed served from
http://localhost:3000
内容的提问来源于stack exchange,提问作者oboualla

