John Anderson John Anderson - 3 months ago 23
Node.js Question

socket.emit not firing inside post request

I wrapped

io.on('connection', function (socket) {
in a post request. I then call
socket.emit('news', 'username taken');
within the post request. For some reason when I make this call it sends nothing to the client. When I change the emit to
io.emit('connection', function (socket))
It works and sends the data to the client. My problem with that solution is using io.emit would send the data to all the sockets that are connected. My question is how can I use socket.emit within this post request.

io.on('connection', onConnection);

function onConnection(sock) {
sock.emit('news', 'username is taken');
}

app.post('/signup', function(req, res) {

var userDetails = User({
firstname: req.body.firstname,
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password1, bcrypt.genSaltSync(10))
});

User.findOne({
$or: [ { 'username': req.body.username}, {'email': req.body.email}]
}, function(err, user) {
if (user) {
if(user.username === req.body.username){
onConnection();
console.log('username is taken');
} else {
}
if(user.email === req.body.email){
console.log('email is taken')
} else {
}
} else {
userDetails.save(function(err) {
if (err) throw err;
});
res.redirect('/');
console.log('change to login')
}
if (err) {
return done(err);
}
});

});

});

Answer

The usual way you would approach this is you would use session middleware that would establish a user session when the first page on the site was loaded. Then, when the user connects with socket.io, you would put the socket.id into the session for that user. Then, when you get the app.post() and you want to send to their socket.io connection, you would look in the session for that user, get the socket.id for that user and then look up the socket using that. Once you have the socket, you can send a message to them.

You use the session to connect the socket.io connection and the app.post(). no event handlers are set inside another event handler.

Comments