6

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

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
user2890027
  • 321
  • 2
  • 13

2 Answers2

0
import { createServer } from "http";
import { Server } from "socket.io";
import express from 'express';

const app = express()

const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: "*"
  }
});

~ by docs - https://socket.io/docs/v4/handling-cors/

Rohit Kaushal
  • 378
  • 3
  • 12
-1

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

egeogretmen
  • 367
  • 2
  • 6