对于较新版本的 socket.io(直到当前的 4.x.x,您需要将 CORS 来源设置为服务器选项的一部分。
CORS 现在被拆分为自己的模块 - 有关详细信息,请参阅 readme。
默认配置是;
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
并限制在一个站点上使用任何子域;
cors: {
origin: [/\.example\.com$/],
methods: ["GET", "POST"]
}
这是一个非常简单/基本的配置块,适合那些不使用 express 或除了原始 socket.io 引擎之外的任何东西的人;
编辑:更新了 socket.io 的第 3 版。
// Options for socket.io => 3.0.0
var options = {
allowUpgrades: true,
transports: [ 'polling', 'websocket' ],
pingTimeout: 9000,
pingInterval: 3000,
cookie: 'mycookie',
httpCompression: true,
cors: '*:*' <---- Allow any origin here [NOTE THE NAME CHANGE]
};
旧版本使用;
// Options for socket.io > 1.0.0
var options = {
allowUpgrades: true,
transports: [ 'polling', 'websocket' ],
pingTimeout: 9000,
pingInterval: 3000,
cookie: 'mycookie',
httpCompression: true,
origins: '*:*' <---- Allow any origin here
};
io = require('socket.io')(8010, options);