Обработка CORS
Настройка
Начиная с Socket.IO v3, необходимо явно включить Cross-Origin Resource Sharing (CORS).
const io = require("socket.io")(httpServer, {
cors: {
origin: "https://example.com",
methods: ["GET", "POST"]
}
}); |
Все параметры будут переданы в пакет cors. Полный список параметров можно найти здесь.
Пример с куки (withCredentials) и дополнительными заголовками:
// server-side
const io = require("socket.io")(httpServer, {
cors: {
origin: "https://example.com",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
// client-side
const io = require("socket.io-client");
const socket = io("https://api.example.com", {
withCredentials: true,
extraHeaders: {
"my-custom-header": "abcd"
}
}); |
Примечание: это также относится к localhost, если веб-приложение и сервер не обслуживаются с одного порта.
const io = require("socket.io")(httpServer, {
cors: {
origin: "http://localhost:8080",
methods: ["GET", "POST"]
}
});
httpServer.listen(3000); |
Отладка
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx/socket.io/?EIO=4&transport=polling&t=NMnp2WI. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). |
Если сервер настроен правильно (см. выше), это может означать, что браузер не смог подключиться к серверу Socket.IO.
Следующая команда:
curl "https://api.example.com/socket.io/?EIO=4&transport=polling" |
должна вернуть что-то вроде:
0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000} |
Если это не так, проверьте, что сервер работает и доступен по указанному порту.
© 2014–2021 Automattic
Licensed under the MIT License.
https://socket.io/docs/v3/handling-cors