Socket.io, NodeJS ve ReactJS CORS hatası
Başlangıç olarak, aynı konuyla ilgili bir sürü soru okudum.
Soketle bağlantıyı React istemcisi üzerinden normal şekilde açtığımda, parametre olarak sadece URL, bu hatayı almıyorum, bağlantı kuruldu.
Ama bunu yaptığımda:
const io = ioClient(webSocketUrl, {
transportOptions: {
polling: {
extraHeaders: getAuthenticationToken()
}
}
});
İstek her seferinde bir CORS hatası döndürüyor.
Denedim:
Menşei şu şekilde ayarlayın:
io.origins(['*:*']);app.use (function (req, res, next) {res.setHeader ("Erişim-Kontrol-İzin Verme", req.header ("kaynak") || req.header ("x-iletilen-ana bilgisayar") | | req.header ("yönlendiren") || req.header ("ana bilgisayar")); res.header ("Erişim Kontrolü-İzin Verme Yöntemleri", "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 ();}) ;
Ve ayrıca bu:
app.use (cors ()); app.options ("*", cors ());
Yukarıdakilerin hiçbiri işe yaramadı.
Herhangi bir yardım için minnettar olurum.
Yanıtlar
Cevabı buldum!
Aynı problemi olan herkes için, işte böyle yaptım:
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();
}
});