dkx22
dkx22

Reputation: 1133

id is not defined (sails.socket.emit)

I'm simply trying to use sails.socket.emit() to send a message and I get this:

error: Sending 500 ("Server Error") response:
 Error (SAILS:HOOK:SOCKETS:USAGE):: `sails.sockets.get()` cannot lookup socket w/o an id (got: `undefined`)

The code in the controller:

sayHiToFriend: function(req, res) {
    var friendId = req.param('id');
    sails.sockets.emit(friendId, 'privateMessage', {from: req.session.userId, msg: 'Hi!'});
    res.json({
      message: 'Message sent!'
    });
}

And client side:

io.socket.get('/user/sayHiToFriend', function serverSays(err,users){

  console.log('with headers: ', JWR.headers);
  console.log('and with status code: ', JWR.statusCode);*/
        if (err)
            console.log(err)

        console.log(JSON.stringify(users));

});

Do I have to pass the id as data to io.socket.get ? If so how? edit: solution:

 sails.sockets.emit(sails.sockets.id(req.socket), 'welcome', {custom: 'data here'});

Upvotes: 1

Views: 645

Answers (1)

Leonardo Lex Minati
Leonardo Lex Minati

Reputation: 31

I had the same problem. It seems like Sails.js has some internal problems or something else we cannot control...in my case few hours ago all worked fine and now it gives that error. I solved it simply compacting the array of the IDs with lodash:

User.findOne({'id': req.body.id}, function(error, user) {
            var subscribers = _.compact(User.subscribers(user));
            sails.sockets.emit(subscribers, "notification", {msg: req.body.msg});
});

and now everything works fine! Hope it helps!

Upvotes: 2

Related Questions