禁用Expres.io中的CORS以进行socket.io调用 [英] Disable CORS in Expres.io for socket.io calls

查看:31
本文介绍了禁用Expres.io中的CORS以进行socket.io调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从角度连接到Express.io套接字,但是出现错误404 CORS.我该如何解决?

I try to connect from angular to a Express.io socket, but I have error 404 CORS. How can I solve this?

XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1447367208172-29. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

如果我直接从浏览器直接加载此路由,则效果很好,但从localhost:80 angular到localhot:3000 express.io无效.

If I load this route directly from browser directly, it works well But from localhost:80 angular to localhot:3000 express.io not works.

在我的express.io中,我禁用了CORS,它对于正常的Ajax请求运行良好,但对于socket.io则无效:

In my express.io I disabled the CORS, and it works well for the normal ajax requests, but not for socket.io :

app.use(function(req, res, next) {
            res.header('Access-Control-Allow-Credentials', true);
            res.header('Access-Control-Allow-Origin',      req.headers.origin);
            res.header('Access-Control-Allow-Methods',     'GET,PUT,POST,DELETE');
            res.header('Access-Control-Allow-Headers',     'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
            next();

});

我在express.io中初始化socket.io:

My initialization of socket.io in express.io:

app.http().io()

推荐答案

您是否正在chrome中运行此有角度的应用程序?我想对于大多数浏览器来说都是相同的方式,但是在chrome上,CORS在本地主机上不起作用:

Are you running this angular app in chrome? I imagine its the same way for most browsers but on chrome CORS will not work with localhost: https://code.google.com/p/chromium/issues/detail?id=67743

我过去为解决此问题所做的就是更改主机(如果在Windows上).如果您不想在Windows上更改主机文件,也可以使用lvh.me而不是localhost.

What I've done to get around this in the past is alter my hosts (if on Windows). You can also use lvh.me instead of localhost if you do not want to alter your hosts file on Windows.

这篇关于禁用Expres.io中的CORS以进行socket.io调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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