【问题标题】:Disable CORS in Expres.io for socket.io calls在 Expres.io 中为 socket.io 调用禁用 CORS
【发布时间】:2016-02-14 10:44:07
【问题描述】:

我尝试从 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()

【问题讨论】:

    标签: node.js express socket.io express.io


    【解决方案1】:

    您是否在 chrome 中运行这个 Angular 应用程序?我想大多数浏览器的方式都是一样的,但在 chrome CORS 上不能与 localhost 一起使用:https://code.google.com/p/chromium/issues/detail?id=67743

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

    【讨论】:

    • 你是在正确的方式。我使用铬,它不适用于本地主机。我在 /etc/hosts 中放置了一个域,它工作正常。谢谢
    猜你喜欢
    • 2019-07-23
    • 2016-09-07
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2020-09-23
    • 2020-08-05
    相关资源
    最近更新 更多