Home > OS >  Returning a JSON array object from the server side in a JavaScript web socket
Returning a JSON array object from the server side in a JavaScript web socket

Time:07-12

Im new to WebSockets and working on sending data from the client side to the server side and back to the client side for a basic chat app. I can send the data to the server side and parse it fine with JSON.parse but when trying to return it to the client side I get an error when trying to parse it. The error is "Unexpected token o in JSON at position 1" Which I believe means its not a JSON object im trying to parse. But don't understand why it changes when sending back to the client side.

Heres the Client Side script that sends the data to the server side:

 var userMessage = messageBox.value;
 var userId = user.value;
  
 ws.send(JSON.stringify({
   text: userMessage,
   id: userId
 }));

The Server side script that catches it and sends it back to the client side:

ws.on('message', function incoming(data) {
    client.send(data);
})

Then back on the Client side I catch the returned data and send it to a function for display like this:

function showMessage(data) {
  const obj = JSON.parse(data);
  const textMessage = obj.text;
  console.log(textMessage);
}

ws.onmessage = ({ data }) => showMessage(data);

CodePudding user response:

Based on your debug logs, it looks like it is a buffer. Try using .toString() method on your object and then do a JSON.parse on the client side.

  • Related