javascript - CORS 与 socket.io

标签 javascript node.js socket.io

我在使用 express.io 的 node.js 应用程序上遇到 CORS 问题。我正在远程托管 socket.io 客户端 js,因为这需要作为远程应用程序工作。

<script src="resources/js/socket.io.min.js"></script>

它托管在 OpenShift 上

服务器.js:

var ipaddr = process.env.OPENSHIFT_NODEJS_IP || "localhost";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var express = require('express.io');
// magical express.io
var app = express();

// Enables CORS
var enableCORS = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');

        // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    } else {
        next();
    };
};

app.configure(function() {
    // enable CORS!
    app.use(enableCORS);

});

app.http().io();
app.io.set('origins', '*:*');
    //.... other stuff
    app.listen(port, ipaddr);

然后在客户端:

var socket = io.connect(window.chat_url);

当我从 localhost:8888 使用服务器 localhost:8080 运行客户端时,socket.io 工作正常。

当我从 localhost:8888 运行客户端并在 odechat-latestsightings.rhcloud.com 上运行服务器时,socket.io 超时:

Firebug : 获取 http://nodechat-latestsightings.rhcloud.com:8888/socket.io/1/?t=1391542144169 1米16秒

其他路线工作正常: 获取 http://nodechat-latestsightings.rhcloud.com/rooms 200 正常 664ms

我就是想不通

最佳答案

此外,如果您的服务器在 openshift 上,那么您应该绑定(bind)到端口:8000 以使用 websockets,因为这是 openshift 的 nginx 反向代理具有公共(public)访问权限的端口。

您可以从此处阅读更多信息:https://developers.openshift.com/en/managing-port-binding-routing.html

关于javascript - CORS 与 socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21561854/

相关文章:

mysql - Node-mysql 发布失败

javascript - 在node.js和socket.io中向单个套接字发送消息

javascript - 使用 Express Router 访问 Express 应用程序

javascript - 错误: Can't set headers after they are sent

javascript - 我在使用毯子的 Mocha 代码覆盖率中获得 0% 覆盖率 0 SLOC

javascript - 套接字IO |如何在服务器端获取客户端传输类型?

android - 如何在nodejs和android中设置实时地理位置跟踪

javascript - 条件语句中未呈现内容

javascript - Angularjs - 在回调函数中分配变量

javascript - 根据 HTML DOM 中类属性的缺失选择元素