简体   繁体   English

Socket.io、NodeJS 和 ReactJS CORS 错误

[英]Socket.io , NodeJS and ReactJS CORS error

As a starter, I have read a bunch of question concerning the same issue.作为初学者,我已经阅读了一堆关于同一问题的问题。

When I open the connection with the socket via React client the normal way, just the URL as parameter, I don't get this error, connection established.当我通过 React 客户端以正常方式打开与套接字的连接时,仅将 URL 作为参数,我没有收到此错误,连接已建立。

But when I do this:但是当我这样做时:

const io = ioClient(webSocketUrl, {
  transportOptions: {
    polling: {
      extraHeaders: getAuthenticationToken()
    }
  }
});

The request return a CORS error everytime.该请求每次都返回 CORS 错误。

I have tried to:我试图:

  • Set the origin like so: io.origins(['*:*']);像这样设置原点: 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(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(); }) ;

  • And also this:还有这个:

    app.use(cors()); app.use(cors()); app.options("*", cors()); app.options("*", cors());

None of the above worked.以上都没有奏效。

I would appreciate any help.我将不胜感激任何帮助。

Found the answer!找到答案了!

For anyone with the same problem, this is how I've done it:对于任何有同样问题的人,我是这样做的:

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();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM