Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io gives CORS error even if I allowed cors it on server

Tags:

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'); 

On server I tried all of following one by one

    1) io.set('origins', '*:*');     2) io.set('origins', 'http://127.0.0.1:5347');     3) io.set('origins', '*');     4) io.set('origins', '127.0.0.1:5347'); 

But I'm getting following error:

XMLHttpRequest cannot load http://127.0.0.1:3001/socket.io/?EIO=3&transport=polling&t=1456799439856-4590. 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.

Note: I'm using express on server and I'm already using cors middleware in following way:

app.use(cors()); 

Where app and cors are instances of express and cors respectively.

like image 301
Akhilesh Kumar Avatar asked Mar 01 '16 02:03

Akhilesh Kumar


1 Answers

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.

like image 128
Akhilesh Kumar Avatar answered Sep 29 '22 15:09

Akhilesh Kumar