Type Error: .join is not a function sockets .io in node client server

Type Error: .join is not a function sockets .io in node client server

我想为我在 node 和 vue js 中构建的聊天应用程序创建一个房间。不幸的是,我不断收到错误消息。join is not a function for socket .io。我知道它是一个服务器端功能,所以我只在服务器端使用它,但问题仍然存在。 .emit() 等所有其他功能都可以正常工作。

这是我的 Index.js

let io = require('./socket')
let server = app.listen(8000)
io = io.init(server)
io.on('connection', socket => {
  console.log('Client Connected')
})

我从 Udemy 的 Maxmilian 的 Node js 大师课程中学习了这段代码。

这是我的 socket.js 导出套接字函数的地方。本质上,我已经创建了一个共享实例来使用其他文件中的套接字。

socket.js

let io

module.exports = {
    init: httpServer => {
        io = require('socket.io')(httpServer,  {
            cors: {
              origin: '*',
              methods: ['GET', 'POST'],
            }
          })
        return io
    },
    getIO: () => {
        if(!io){
            console.log('Socket is not Initialized')
        }
        return io
    } 
}

最后但并非最不重要的是我的 customer_controller.js 我尝试加入 socket.join() customer_controller.js

exports.getMessages = async(req, res, next) => {
  try {
    let messages = await Message.find({
      users: [ req.user.email, 'admin@demo.com' ] })
      .populate('sender')
      .sort({"updatedAt": 1})
    io.getIO().join(req.user.email)
    res.json(messages)
  } catch(err) {
    console.log(err)
  }
}

这是我的详细错误!

TypeError: io.getIO(...).join is not a function

如果有人想知道解决方案。应该是:

io.getIO(socket => {
      socket.join(req.user.email)
    })

而不是

io.getIO().join(req.user.email)

因为 socket 有一个名为 .join() 的函数,而不是 io。这是文档。仔细看我错过了好几次。虽然我仍然面临有关控制台日志记录的问题 socket.rooms

当我做的时候

console.log(socket.rooms)

在 customer_controller.js 中,它 returns 什么都没有,甚至是错误。但是当我在 index.js 文件中这样做时:

index.js

io.on('connection', socket => {
   console.log(socket.rooms)
})

就returns一套。如果有人有更有效的方法来处理这个问题,请 post 您的回答。我接受它作为解决方案。谢谢