为了账号安全,请及时绑定邮箱和手机立即绑定

Socket.io、NodeJS 和 ReactJS CORS 错误

Socket.io、NodeJS 和 ReactJS CORS 错误

茅侃侃 2023-04-20 10:50:16
作为初学者,我已经阅读了很多关于同一问题的问题。当我以正常方式通过 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();

  }

});


查看完整回答
反对 回复 2023-04-20
  • 1 回答
  • 0 关注
  • 84 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信