简体   繁体   English

如何通过socket.io或http或Express发送JSON

[英]How to send JSON via socket.io or http or Express

I have this on the server: 我在服务器上有这个:

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

And this on the client: 而在客户端上:

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

And I got this on node.js console instead of my message: 我在node.js控制台上收到了这个消息,而不是我的消息:

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

Please help me to send my json from client to server and tell what I'm doing wrong. 请帮助我将json从客户端发送到服务器,并告诉我我在做什么错。
And sorry for my English. 对不起,我的英语。

You doesn't need to parse JSON in on event. 您不需要on事件中解析JSON。 Just use message variable as object. 只需将消息变量用作对象即可。

For example: 例如:

 console.log(message.message);

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

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