Socket.io、NodeJS 和 ReactJS CORS 错误

作为初学者,我已经阅读了很多关于同一问题的问题。


当我以正常方式通过 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());

以上均无效。

我将不胜感激任何帮助。


茅侃侃
浏览 86回答 1
1回答

白板的微信

找到答案了!对于有同样问题的任何人,这就是我的做法: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();  }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript