簡體   English   中英

Socket.io、NodeJS 和 ReactJS CORS 錯誤

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

作為初學者,我已經閱讀了一堆關於同一問題的問題。

當我通過 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());

以上都沒有奏效。

我將不勝感激任何幫助。

找到答案了!

對於任何有同樣問題的人,我是這樣做的:

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