作为初学者,我已经阅读了很多关于同一问题的问题。当我以正常方式通过 React 客户端打开与套接字的连接时,仅将 URL 作为参数,我没有收到此错误,连接已建立。但是当我这样做时:const io = ioClient(webSocketUrl, { transportOptions: { polling: { extraHeaders: getAuthenticationToken() } }});该请求每次都返回 CORS 错误。我试图:像这样设置原点:io.origins(['*:*']);app.use(function (req, res, next) { res.setHeader( "Access-Control-Allow-Origin", req.header("origin") || req.header("x-forwarded-host") | | req.header("referer") || req.header("host") ); res.header( "Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE" ); res.header("Access-Control-Allow-Headers", "X-Requested-With,content-type"); res.setHeader("Access-Control-Allow-Credentials", false); next(); }) ;还有这个:app.use(cors()); app.options("*", cors());以上均无效。我将不胜感激任何帮助。
1 回答
白板的微信
TA贡献1883条经验 获得超3个赞
找到答案了!
对于有同样问题的任何人,这就是我的做法:
const io = require("socket.io")(server, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
添加回答
举报
0/150
提交
取消