Question

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:

[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 me what am I doing wrong.

Was it helpful?

Solution

You doesn't need to parse JSON in on event. Just use message variable as object.

For example:

 console.log(message.message);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top