Socket connection with Heroku (CORS issue?)


#1

Hello.

I’m trying to set up a simple socket.io 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://ionic-tictactoe.herokuapp.com:22837');
    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(cors());
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', "http://"+req.headers.host+':8100');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  next();
  }
);

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

io.on('connection', function(socket){
  socket.on('login', function(username){
    users.addUser(username, socket.id, function(users){
      io.sockets.emit('refreshUserList', users);
    });
  });
  socket.on('invite', function(socketid, username){
    //console.log('broadcasting to ' + socketid + ' from ' + socket.id);
    socket.broadcast.to(socketid).emit('invitation', {socket: socket.id, name: username});
  });
  socket.on('disconnect', function(){
    users.removeUser(socket.id, function(users){
      io.sockets.emit('refreshUserList', users);
    });
  });
  socket.on('start', function(partnerSocket, partnerXorO){
    socket.emit('start', partnerSocket);
    socket.broadcast.to(partnerSocket).emit('start', socket.id, partnerXorO);
  });
  socket.on('move', function(partnerSocket, index, symbol){
    socket.broadcast.to(partnerSocket).emit('move', index, symbol);
  });
  socket.on('win', function(partnerSocket){
    socket.broadcast.to(partnerSocket).emit('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('Socket.io Running on port ' + app.get('port') );
});

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

Tony


#2

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

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