0

I need some help here. I need to set user username and do not change it. But the problem is everytime I join with new user it;s username is added to session and then all users are typing as the latest user who joined. How to solve this problem ? This is the code:

let users = [];
let username;

app.post('/join-server', async(req, res) => {
    username = await req.body.username;
    users.push(username);
    req.session.username = username;
    res.redirect('/chatroom');
});

socket.on('message-sent', (data) => {
   io.emit('message-broadcast', ({
            message: data.message,
            username: username
        }));
    });
zlotte
  • 201
  • 1
  • 8

1 Answers1

0

Your username variable has been declared in global scope. Declare it within the body of your /join-server handler instead:

app.post('/join-server', async(req, res) => {
    const username = await req.body.username;
    users.push(username);
    req.session.username = username;
    res.redirect('/chatroom');
});
Connor
  • 1,465
  • 2
  • 14
  • 24
  • But how then use it in my socket emit ? – zlotte Dec 05 '18 at 21:42
  • 1
    You'll either need to send a way to identify the user along with the message they typed from your client, or look into a middleware solution for sharing sessions between your ExpressJS application and your Socket.IO server. Here's an interesting-looking approach you might consider: https://stackoverflow.com/questions/25532692/ – Connor Dec 05 '18 at 21:46
  • No worries! Glad that took you in a positive direction. – Connor Dec 05 '18 at 21:53