chatcord icon indicating copy to clipboard operation
chatcord copied to clipboard

App crashing..getting 'room' not defined in console.

Open Ayush909 opened this issue 4 years ago • 9 comments

here is my console error `C:\Users\user\Desktop\Backend Projects\Rooms-Users-Chatapp\chatapp2\server.js:77 io.in(user.room).emit('roomUsers',{ ^

TypeError: Cannot read property 'room' of undefined`

here is my server.js :-

`

const path = require('path');
const http = require('http');
const express = require('express');
const formatMessage = require('./utils/message');
const {userJoin, getCurrentUser, userLeave, getRoomUsers } = require('./utils/users');
const app = express();
const socketio = require('socket.io');
const fs = require('fs');

const server = http.createServer(app);

const io = socketio(server);

app.use(express.static(path.join(__dirname,'public')));

const botname = 'Dechat Bot';

io.on('connection', socket=>{

    //join Room
    socket.on('joinRoom', ({username,room})=>{

        const user = userJoin(socket.id, username , room);

        socket.join(user.room);

        //Welcome message to the user only
        socket.emit('message', formatMessage(botname,'Welcome to Dechat'));

        //Notifies all users when a new user connects except the user that connects
        socket.broadcast
        .to(user.room)
        .emit(
            'message',formatMessage(botname,`${user.username} has joined the chat.`)
        );

        //sending users and room info to client page
        io.emit('roomUsers',{
            room: user.room,
            users: getRoomUsers(user.room)
        });  
        
        //uploading image
        socket.on('upload-image',(message)=>{
            if(message.size < 500000){
                var writer = fs.createWriteStream(path.resolve(__dirname,'./public/images/'+message.name),{
                    encoding: 'base64'
                });  
                writer.write(message.data);
                writer.end();
                
                writer.on('finish',()=>{
                    io.to(user.room).emit('image-uploaded',{
                        name: '/images/' + message.name
                    });
                });
            }      

        });
    });
        
    //Listen to chatMessage
    socket.on('chatMessage', msg=>{
        const user = getCurrentUser(socket.id);
        io.to(user.room).emit('message',formatMessage(user.username,msg));
    })
 //Notifies all users when a user disconnects
    socket.on('disconnect',()=>{
        const user = userLeave(socket.id);
        if(user){
            io.to(user.room).emit('message',formatMessage(botname,`${user.username} has left the chat`));
        }
        //sending users and room info to client page
        io.in(user.room).emit('roomUsers',{
            room: user.room,
            users: getRoomUsers(user.room)
        });
    })


})
const PORT = process.env.PORT || 3000;

server.listen(PORT, ()=>{
    console.log(`Server running on ${PORT}`);
})`

Ayush909 avatar Apr 28 '20 17:04 Ayush909

https://github.com/Ayush909/dechat1.0 here is my repo Please help

Ayush909 avatar Apr 28 '20 17:04 Ayush909

Should be io.to(user.room) instead of io.in(user.room). Check my repo at https://github.com/Somsubhra1/ChatSpace.

Somsubhra1 avatar Apr 29 '20 11:04 Somsubhra1

Should be io.to(user.room) instead of io.in(user.room). Check my repo at https://github.com/Somsubhra1/ChatSpace.

Still getting the same error.

Ayush909 avatar Apr 30 '20 04:04 Ayush909

In @Ayush909's code you can see a surrounding if conditional that you are missing @Somsubhra1 https://github.com/Somsubhra1/ChatSpace/blob/master/server.js#L72-L82

If that doesn't help, I suggest console logging or using debug to find what properties exist in the user object to ensure that it's not appearing as null or without a room.

leslie-alldridge avatar May 11 '20 06:05 leslie-alldridge

Was this issue ever solved? I have the exact same issue. I have a feeling the users[] array is not persisting, because whenever I print out the array using .map, I get: id: undefined, username: undefined, room: undefined multiple times. I am going to try to save the array to a file for persistence and see if this works.

DanielGannage avatar Jul 22 '20 15:07 DanielGannage

There was never a problem in the first place.. I followed the tutorial and it worked fine. Feel free to link your repo

leslie-alldridge avatar Jul 23 '20 06:07 leslie-alldridge

Found the issue, on the client side I was instantiating multiple io() objects. This was opening multiple connections per browser session. The multiple connections created multiple socket.ids which did not work well with return users.find(user => user.id === id); - basically returning undefined

DanielGannage avatar Jul 23 '20 19:07 DanielGannage

@Ayush909 How did you get the solution later? I am facing the exact same issue?

upendradhamala avatar Dec 14 '20 15:12 upendradhamala

Hi there, this is my code https://github.com/egin10/anonymous-chat It's work properly. Hope it can help you guys.

egin10 avatar Jan 26 '21 19:01 egin10