doc suggestion: do not use express app.listen() with socket.io
I ran into this in the process of adding socket.io to an existing express(4) app because i didn't switch the code from app.listen() to server.listen().
The symptom is refusal by the server to serve the client library or connect any sockets.
According to http://expressjs.com/4x/api.html#app.listen , "This method is identical to node's http.Server.listen()" - but in reality it creates a new http server leaving the one with socket.io non-operational.
Hopefully this issue will help others to avoid the same trap.
Could you please provide a full example? Been dealing with these changes due to new express, and it's not obvious to me what the "server" would be in this case, especially when trying to pass in custom "use" settings. Thanks.
Our original project used regular express boilerplate:
var express = require('express');
var app = express();
// ... other code
app.listen(port);
the socket.io documentation here says
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
so i fixed the first part of the code in our project, but i didn't change app.listen() to server.listen() because i thought they were the same, and things kindof worked except socket.io didn't run...
+1
Did a bit more research and found a way (more details here) to stick with app.listen():
var io = require("socket.io").listen(server);
app.set("port", (process.env.PORT || 3000));
var server = app.listen(app.get("port"), function(){
console.log("Server started: http://localhost:" + app.get("port") + "/");
})
which seems to work the same as:
var io = require("socket.io")(server);
var server = require('http').Server(app);
server.listen((process.env.PORT || 3000), function(){
console.log("Server started: http://localhost:" + app.get("port") + "/");
});
For folks passing by looking for answer to you CORS issue, express.listen() causes "No 'Access-Control-Allow-Origin' header is present on the requested resource." CORSs error, whereas http.listen() does not.
This is indeed a common trap... A note was added here: https://socket.io/docs/v3/server-initialization/#With-Express
is there any limitations if we use server created from
const expressServer = app.listen(4000)
to implement socket.io server
const io = new Server(expressServer,{
cors: [
'http://localhost:4000'
]
})