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 ());
위의 어느 것도 작동하지 않았습니다.
도움을 주시면 감사하겠습니다.
답변
답을 찾았습니다!
같은 문제가있는 사람을 위해 이렇게했습니다.
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();
}
});