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

查看:118
本文介绍了即使我允许在服务器上使用cors,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 。当凭据标记为true时,通配符'*'不能用于'Access-Control-Allow-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.

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

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