在 Expres.io 中为 socket.io 调用禁用 CORS

Disable CORS in Expres.io for socket.io calls

我尝试从 angular 连接到 Express.io 套接字,但出现错误 404 CORS。我该如何解决这个问题?

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 不行。

在我的 express.io 中,我禁用了 CORS,它适用于正常的 ajax 请求,但不适用于 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 的初始化:

app.http().io()

你运行这个angular应用在chrome吗?我想它对大多数浏览器来说都是一样的,但是在 chrome 上,CORS 将无法与本地主机一起工作:https://code.google.com/p/chromium/issues/detail?id=67743

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