node.js - id 未定义(sails.socket.emit)

标签 node.js sockets undefined sails.js

我只是尝试使用 sails.socket.emit() 发送消息,我得到了这个:

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

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!'
    });
}

和客户端:

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));

});

我是否必须将 id 作为数据传递给 io.socket.get ?如果是这样怎么办? 编辑:解决方案:

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

最佳答案

我也遇到了同样的问题。看起来 Sails.js 存在一些内部问题或其他我们无法控制的问题...就我而言,几个小时前一切正常,现在却出现了该错误。我简单地用 lodash 压缩 ID 数组就解决了这个问题:

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

现在一切正常!希望对您有帮助!

关于node.js - id 未定义(sails.socket.emit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587711/

相关文章:

javascript - 奇怪的 JavaScript 输出

node.js - socket.io/1/?t=1437482662157 404 未找到

javascript - node.js - 表达 - res.render() : Correct format for feeding variables into the JSON parameter?

c# - 如何将 PFX 证书文件应用于 SslStream 套接字监听器?

c - 尝试与线程之间的套接字建立内部连接并连接失败

jquery - 为什么我的所有 jQuery cookie 都未定义?

javascript - 分片时启动代码时出现 UnhandledPromiseRejectionWarning

javascript - 快捷支付 : An unknown error happened. 请重试

objective-c - 如何在 Objective-C 中使用本地域套接字

javascript - 使用 eval() 定义变量显示未定义错误