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

后端 未结 5 1942
名媛妹妹
名媛妹妹 2020-12-17 15:31

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


        
相关标签:
5条回答
  • 2020-12-17 15:36

    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();
    });
    
    0 讨论(0)
  • 2020-12-17 15:49

    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.

    0 讨论(0)
  • 2020-12-17 15:51

    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);
    
    0 讨论(0)
  • 2020-12-17 15:55

    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"],
    }
    
    0 讨论(0)
  • 2020-12-17 15:55

    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.

    0 讨论(0)
提交回复
热议问题