ilellouch ilellouch - 2 months ago 69
Node.js Question

Add socket.io on nodejs

I'm testing socket.io with nodejs.

This is what I have on my server side :

var app = express();
app.set('port', process.env.PORT || 3000);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
next();
});
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});

var http = require('http').Server(app);
var io = require('socket.io')(http);


io.on('connection', function(socket){
console.log('a user connected');
});


And this is what I have on my client side :

var socket = io("http://localhost:3000");


And I get a 404 :

socket.io-1.4.5.js:1 GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LTYKOs3
XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=3&transport=polling&t=LTYKOs3. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.


I've been looking on forums to get answers about origins and adding information to header, but nothing seems to work.

Any help plz ?
Thanks

Answer

Change these lines of code:

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

var http = require('http').Server(app);
var io = require('socket.io')(http);

to this:

var server = app.listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});

var io = require('socket.io')(server);

Your code was creating a second server that was not on port 3000 and binding socket.io to that other server so when you tried to use socket.io on port 3000, it wasn't connecting to the a server that had socket.io on it. My code suggestion binds socket.io to the one express server on port 3000 and does not create a second server.