简体   繁体   English

如何使用socket.io发出对象?

[英]How to emit object using socket.io?

I have a code like, I have a problem with sending response. 我有类似的代码,我在发送响应时遇到问题。

socket.on('findUserMessages', (userName) => {
    io.sockets.connected[socket.id].emit('Checking-message', {
        type: 'ss',
        text: bot,
        user: 'bot'
    });

    var dupa = db.chat.find({ user: userName }, function(err, docs) {
        userName = userName
        if (err) throw err;
        console.log('load old messages', docs)
    })

    io.emit('private message', dupa);
})

My node console output is like 我的节点控制台输出就像

[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]

I know that output is not a JSON string, how to solve that? 我知道输出不是JSON字符串,如何解决? I was trying to use .toArray() but without succes. 我试图使用.toArray()但没有成功。

That might be silly question but I am stuck with it for a long time. 这可能是一个愚蠢的问题,但我坚持了很长时间。

Convert to json your result before emitting it. 在发出结果之前将其转换为json。 Try to emit JSON.stringify(dupa) . 尝试发出JSON.stringify(dupa)

EDIT Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there ( JSON.strigify(result) on client side on receiving the emit event). 编辑您的输出实际上已经是JSON(JSON数组),因此,如果您只想在客户端获取JSON字符串,请将您的输出转换为在那里的字符串(在客户端接收到emit事件时, JSON.strigify(result) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM