Socket connection with Heroku (CORS issue?)


I’m trying to set up a simple connection, with a server running Express.js hosted on Heroku. The socket works fine when hosted on localhost and accessed from the browser using ionic serve, but I can’t get the client to connect to the Heroku-hosted server, either from a browser or from a device. Firefox console gives me a “Cross-Origin Request Blocked” error. My Socket factory is here:

.factory('SOCKET', function(){
    //var socket=io('localhost:5000');
    var socket=io('ws://');
    return socket;

The server app.js is here (the commented-out app.use(cors()) line did not work).

var app = require('express')();
var cors = require('cors');

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', "http://"':8100');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

var server = require('http').Server(app);
var io = require('')(server);
var users = require('./lib/users.js')

io.on('connection', function(socket){
  socket.on('login', function(username){
    users.addUser(username,, function(users){
      io.sockets.emit('refreshUserList', users);
  socket.on('invite', function(socketid, username){
    //console.log('broadcasting to ' + socketid + ' from ' +;'invitation', {socket:, name: username});
  socket.on('disconnect', function(){
    users.removeUser(, function(users){
      io.sockets.emit('refreshUserList', users);
  socket.on('start', function(partnerSocket, partnerXorO){
    socket.emit('start', partnerSocket);'start',, partnerXorO);
  socket.on('move', function(partnerSocket, index, symbol){'move', index, symbol);
  socket.on('win', function(partnerSocket){'lose');

app.set('port', (process.env.PORT || 5000));

app.get('/', function (req, res) {
  res.send('Running on port ' + app.get('port'))

server.listen(app.get('port'), function(){
  console.log(' Running on port ' + app.get('port') );

If anybody can see what I’m doing wrong, I’d appreciate it!


A little late, but just posting for anyone else having this issue.
Try using port 80:
var socket=io('ws://');

This seemed to work for me after a couple hours of searching and trying a number of different things.

1 Like