Reputation: 33
I'm building a project using socket.io. while running getting the error "TypeError: Cannot read property 'emit' of undefined".
server code is given below:
server.js
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)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
Can anyone help to rectify the error?
Upvotes: 3
Views: 2819
Reputation: 2512
socket.io
version 2.0.3
'4.0.1'
.
Apparently in this version, the broadcast
property is no longer
available/has been removed which is why you are getting the above TypeError.'to()'
method on the io
object instead of the socket
object.Solution:
Replace this:
socket.to(roomId).broadcast.emit('user-connected', userId)
With this:
io.to(roomId).emit('user-connected', userId);
For further information, please refer this documentation: Socket.io rooms
Upvotes: 0
Reputation: 106
It seems that your socket function is written in the wrong order
Try this:
socket.broadcast.to(roomId).emit('user-connected', userId)
and this:
socket.broadcast.to(roomId).emit('user-disconnected', userId)
Upvotes: 2