Reputation: 1326
This is my code
if((typeof session) !== undefined && (typeof session.username) !== undefined){
data = session.username+" online";
io.sockets.emit('update_common_message',data);
socketsOfClients[session.username].push(socket.id);
}
I am getting error
TypeError: Cannot read property 'username' of undefined
I dont know what is the wrong with my code...
Upvotes: 0
Views: 268
Reputation: 8427
I think, this would suffice, looks cleaner too.
if (session && session.username) {
data = session.username + " online";
io.sockets.emit('update_common_message', data);
socketsOfClients[session.username].push(socket.id);
}
Upvotes: 1
Reputation: 3478
Your problem is that typeof
returns a string:
if((typeof session) !== 'undefined' && (typeof session.username) !== 'undefined'){
// ...
}
Upvotes: 1
Reputation: 203494
typeof
returns a string, so you need to test against a string too:
if ((typeof session) !== 'undefined' ...)
Upvotes: 2