类型错误:无法读取 Socket.socket.on 处未定义的属性“emit”

时间:2021-03-22 14:51:30

标签: node.js socket.io

我不知道这段代码有什么问题,有人可以帮我吗?尝试了很多方法,还是不行

const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')

app.set('view engine', 'ejs')
app.use(express.static('public'))

app.get('/', (req, res) => {
    res.redirect(`/${uuidV4()}`)
})

app.get('/:room', (req, res) => {
    res.render('room', { roomId: req.params.room })
})

io.on('connection', socket => {
    socket.on('join-room', (roomId, userId) => {
        socket.join(roomId)
        socket.to(roomId).broadcast.emit('user-connected', userId)
    })
})

server.listen(3000)

1 个答案:

答案 0 :(得分:0)

改变这个:

socket.to(roomId).broadcast.emit('user-connected', userId)

到:

socket.broadcast.to(roomId).emit('user-connected', userId)