简体   繁体   中英

Listen to Socket.io server after require

When I'm activating the io server right after require it works fine, but when I want to do after require my code gives an error when it reaches the first interaction with io (defining middleware in my case).

This is working fine:

const io = require('socket.io').listen(3002);

const { authValidation } = require('./middlewares');

//Middlewares
io.use(authValidation);
. . .

This one gives an error:

const io = require('socket.io');

const { authValidation } = require('./middlewares');

io.listen(3002, () => {
  console.log(`Listening to port 3002`);
});

//Middlewares
io.use(authValidation);
. . .

The error says that io.use() is not a function. I think there is a problem related to the code execution flow and asynchronous stuff, but I can't say what exactly.

Maybe try this? I haven't worked with socket.io in a while, but I remember it was something like this.

What this does differently is setting io to the return value of the listen method.

const socket = require('socket.io');

const { authValidation } = require('./middlewares');

const io = socket.listen(3002, () => {
  console.log(`Listening to port 3002`);
});

//Middlewares
io.use(authValidation);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM