My node server and client are running on different ports(3001,5347 respectively). On client I had used,
var socket = io(\'http://127.0.0.1:3001\');
If you are using Express then define a middleware like this before your serve start code...
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
If running Express as follows:
var app = express();
var server = app.listen(3000);
So to start socket.io, we can do the following:
var io = require('socket.io').listen(server);
The problem was because of following code:
var http = require('http').Server(app);
var io = require('socket.io')(http);
The server object passed to socket.io was not the same as the server object I'm listening on.
Following code helped:
const PORT = process.env.PORT || 4000;
const app = express();
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
const io = socket(server);
The accepted answer is outdated
According to the official docs, you can add it to an existing http Server https://socket.io/docs/server-initialization/#Attached-to-an-existing-HTTP-server
const server = require('http').createServer();
const options = { /* ... */ };
const io = require('socket.io')(server, options);
io.on('connection', socket => { /* ... */ });
server.listen(3000);
to enable cors using this options object seemed to do the trick
options={
cors:true,
origins:["http://127.0.0.1:5347"],
}
Note that you can use cors() with app before you pass app into require('http'), which is then passed into socket.io. In this order. This should work too.
const app = express();
app.use(cors());
const http = require('http').Server(app);
const io = require('socket.io')(http);
Hope it helps.