在 Expres.io 中为 socket.io 调用禁用 CORS [英] Disable CORS in Expres.io for socket.io calls

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

问题描述

我尝试从 angular 连接到 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 中运行此 Angular 应用程序?我想它对大多数浏览器来说都是一样的,但在 chrome CORS 上不能与本地主机一起使用:https://code.google.com/p/chromium/issues/detail?id=67743

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 中为 socket.io 调用禁用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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