【问题标题】:How to send JSON via socket.io如何通过 socket.io 发送 JSON
【发布时间】:2014-06-28 14:27:00
【问题描述】:

我在服务器上有这个:

io.sockets.on('connection', function (client) {
    client.on('message', function (message) {
        try {
            var incomingJSON = JSON.parse(message);
            console.log("Message received");
            console.log(incomingJSON.message);
            console.log(incomingJSON.coordinates);
        } catch (e) {
            console.log(e);
            client.disconnect();
        }
    });
});

这在客户端:

var socket = io.connect('http://localhost:8008');
$("#ready").click(function(){
    socket.emit("message", {message: "ready", coordinates: "21"});
});

我在 node.js 控制台而不是我的消息上得到了这个:

[SyntaxError: Unexpected token o]
info: booting client
info: transport end by forced client disconnection
debug: websocket writing 0::
info: transport end (booted)

请帮我将我的 JSON 从客户端发送到服务器,并告诉我我做错了什么。

【问题讨论】:

    标签: javascript json node.js sockets socket.io


    【解决方案1】:

    您不需要在 on 事件中解析 JSON。 只需使用消息变量作为对象。

    例如:

     console.log(message.message);
    

    【讨论】:

    • 祝 nodejs 好运 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多