John Anderson John Anderson - 2 months ago 16
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');
}'/signup', function(req, res) {

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

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




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, you would put the into the session for that user. Then, when you get the and you want to send to their connection, you would look in the session for that user, get the 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 connection and the no event handlers are set inside another event handler.