即使我在服务器上允许它,Socket.io 也会出现 CORS 错误 [英] Socket.io gives CORS error even if I allowed cors it on server

查看:25
本文介绍了即使我在服务器上允许它,Socket.io 也会出现 CORS 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的节点服务器和客户端运行在不同的端口上(分别为 3001,5347).在我使用过的客户端上,

My node server and client are running on different ports(3001,5347 respectively). On client I had used,

var socket = io('http://127.0.0.1:3001');

在服务器上我一一尝试了所有的

On server I tried all of following one by one

    1) io.set('origins', '*:*');
    2) io.set('origins', 'http://127.0.0.1:5347');
    3) io.set('origins', '*');
    4) io.set('origins', '127.0.0.1:5347');

但我收到以下错误:

XMLHttpRequest 无法加载 http://127.0.0.1:3001/socket.io/?EIO=3&transport=polling&t=1456799439856-4590.当凭证标志为真时,不能在Access-Control-Allow-Origin"标头中使用通配符*".因此不允许访问 Origin 'null'.

XMLHttpRequest cannot load http://127.0.0.1:3001/socket.io/?EIO=3&transport=polling&t=1456799439856-4590. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.

注意:我在服务器上使用 express,并且我已经通过以下方式使用 cors 中间件:

Note: I'm using express on server and I'm already using cors middleware in following way:

app.use(cors());

其中 app 和 cors 分别是 express 和 cors 的实例.

Where app and cors are instances of express and cors respectively.

推荐答案

如果运行Express如下:

If running Express as follows:

var app = express();
var server = app.listen(3000);

所以要启动socket.io,我们可以这样做:

So to start socket.io, we can do the following:

var io = require('socket.io').listen(server);

问题是因为以下代码:

var http = require('http').Server(app);
var io = require('socket.io')(http);

传递给 socket.io 的服务器对象与我正在监听的服务器对象不同.

The server object passed to socket.io was not the same as the server object I'm listening on.

这篇关于即使我在服务器上允许它,Socket.io 也会出现 CORS 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆