ข้อผิดพลาด Socket.io, NodeJS และ ReactJS CORS

Oct 06 2020

ในฐานะผู้เริ่มต้นฉันได้อ่านคำถามมากมายเกี่ยวกับปัญหาเดียวกัน

เมื่อฉันเปิดการเชื่อมต่อกับซ็อกเก็ตผ่านไคลเอนต์ React ด้วยวิธีปกติเพียงแค่ URL เป็นพารามิเตอร์ฉันไม่ได้รับข้อผิดพลาดนี้สร้างการเชื่อมต่อแล้ว

แต่เมื่อฉันทำสิ่งนี้:

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

คำขอส่งคืนข้อผิดพลาด CORS ทุกครั้ง

ฉันได้พยายาม:

  • กำหนดจุดเริ่มต้นดังนี้: io.origins(['*:*']);

  • app.use (ฟังก์ชัน (req, res, ถัดไป) {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 ());

ข้างต้นไม่ได้ผล

ฉันอยากจะขอบคุณความช่วยเหลือใด ๆ.

คำตอบ

Rodolfo Oct 07 2020 at 12:37

พบคำตอบ!

สำหรับใครที่มีปัญหาเดียวกันนี่คือวิธีที่ฉันได้ทำไปแล้ว:

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