跳至主要内容
版本:4.x

处理 CORS

配置

从 Socket.IO v3 开始,您需要显式启用 跨域资源共享 (CORS)。

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "https://example.com"
}
});

所有选项将转发到 cors 包。完整的选项列表可以在 这里 找到。

带有 cookie 的示例 (withCredentials) 和附加的标头

// server-side
const io = new Server(httpServer, {
cors: {
origin: "https://example.com",
allowedHeaders: ["my-custom-header"],
credentials: true
}
});

// client-side
import { io } from "socket.io-client";
const socket = io("https://api.example.com", {
withCredentials: true,
extraHeaders: {
"my-custom-header": "abcd"
}
});

注意:如果您的 Web 应用程序和服务器不是从同一个端口提供服务的,这也适用于 localhost

const io = new Server(httpServer, {
cors: {
origin: "http://localhost:8080"
}
});

httpServer.listen(3000);

您可以使用 allowRequest 选项禁止所有跨域请求

const io = new Server(httpServer, {
allowRequest: (req, callback) => {
const noOriginHeader = req.headers.origin === undefined;
callback(null, noOriginHeader); // only allow requests without 'origin' header
}
});

故障排除

CORS 标头“Access-Control-Allow-Origin” 丢失

完整错误消息

跨域请求被阻止:同源策略不允许读取 .../socket.io/?EIO=4&transport=polling&t=NMnp2WI 的远程资源。(原因:CORS 标头“Access-Control-Allow-Origin” 丢失)。

如果您已正确配置服务器(请参阅 上面),这可能意味着您的浏览器无法访问 Socket.IO 服务器。

以下命令

curl "https://api.example.com/socket.io/?EIO=4&transport=polling"

应该返回类似于

0{"sid":"Lbo5JLzTotvW3g2LAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}

如果情况并非如此,请检查您的服务器是否正在监听,并且实际上可以在给定端口上访问。

如果 CORS 标头“Access-Control-Allow-Origin” 为“*”,则不支持凭据

完整错误消息

跨域请求被阻止:同源策略不允许读取“.../socket.io/?EIO=4&transport=polling&t=NvQfU77”的远程资源。(原因:如果 CORS 标头“Access-Control-Allow-Origin” 为“*”,则不支持凭据)。

您不能将 withCredentials 设置为 trueorigin: *,您需要使用特定的来源

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: "https://my-frontend.com",
// or with an array of origins
// origin: ["https://my-frontend.com", "https://my-other-frontend.com", "http://localhost:3000"],
credentials: true
}
});

CORS 标头“Access-Control-Allow-Credentials” 中预期为“true”

完整错误消息

跨域请求被阻止:同源策略不允许读取 .../socket.io/?EIO=4&transport=polling&t=NvQny19 的远程资源。(原因:CORS 标头“Access-Control-Allow-Credentials” 中预期为“true”)。

在这种情况下,withCredentials 在客户端被设置为 true,但服务器在 cors 选项中缺少 credentials 属性。请参阅上面的示例。