使用socket.io时,要在使用socket.io时发生错误,但仅当用户断开连接并再次连接时。为什么这会发生?

问题描述 投票:0回答:1
当前端已经运行时,我不会遇到任何错误,然后启动服务器。插座连接是没有任何问题的。 但是,如果我断开前端的连接并重新开始,它会给我cors错误: 错误看起来像这样:

Access to XMLHttpRequest at 'http://localhost:3001/socket.io/?EIO=4&transport=polling&t=pypdmqlh' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
这是插座托:

export const registerSocketServer = (server: HttpServer) => { const io = new Server< ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData >(server, { cors: { // origin: true, origin: [`${process.env.FRONTEND_URL}`, "*"], methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], credentials: true, // allowedHeaders: "*", allowedHeaders: [ "Content-Type", "AccessKey", "st-auth-mode", "rid", "x-file-name", "x-start-byte", "x-end-byte", "x-total-size", "content-type", "Access-Control-Max-Age", "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", "Access-Control-Allow-Headers", ...getAllCORSHeaders(), ], }, // allow max 10mb file maxHttpBufferSize: 1e7, });
这是服务器中的CORS设置:

app.use( cors({ origin: [`${process.env.FRONTEND_URL}`, "*"], // // origin: "*", //allow all // // allowedHeaders: ["content-type", ...getAllCORSHeaders()], allowedHeaders: [ "Content-Type", "AccessKey", "st-auth-mode", "rid", "x-file-name", "x-start-byte", "x-end-byte", "x-total-size", "content-type", "Access-Control-Max-Age", "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", "Access-Control-Allow-Headers", ...getAllCORSHeaders(), ], methods: ["GET", "POST", "PUT", "DELETE"], credentials: true, // Ensure credentials are allowed }), );
    
sockets websocket socket.io cors
1个回答
0
投票
听起来您的问题会发生在前端重新连接时,这可能是由于过时的CORS设置或如何处理前请求的处理方式。您可能想尝试的几件事:

1️⃣而不是[“ $ {process.env.frontend_url}”,“

”],尝试Just Process.env.frontend_url。与凭据一起使用“”可能会导致冲突。 2️⃣确保选项包含在允许的方法中,因此飞行前请求正确通过。 3️⃣尝试在重新连接之前手动断开插座的连接 - 它可以保持旧会话。 如果它仍然行动起来,则在问题发生时记录请求标题可能会为您提供更多线索。希望这有帮助!

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.