简体   繁体   中英

CORS with socket.io

I'm having trouble with CORS on a node.js app using express.io. I'm hosting the socket.io client js remotely since this needs to works as a remote app.

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

It's hosted on OpenShift

server.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);

Then on the client:

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

When I run the client from localhost:8888 with the server localhost:8080 socket.io works fine.

When I run the client from localhost:8888 and the server on odechat-latestsightings.rhcloud.com then socket.io times out:

Firebug: GET http://nodechat-latestsightings.rhcloud.com:8888/socket.io/1/?t=1391542144169 1m 16s

The other routes work fine: GET http://nodechat-latestsightings.rhcloud.com/rooms 200 OK 664ms

I just can't figure this out

http://nodechat-latestsightings.rhcloud.com/socket.io/1/?t=1391542144169 seems to work fine

that is whthout the port number in the url, what is the port your binding to?

Also, if your server is on openshift then you should bind to port: 8000 to use websockets since that is the port openshift's nginx reverse proxy has public access.

You can read more from here: https://developers.openshift.com/en/managing-port-binding-routing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM