我在使用 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/