1

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);
13
  • 3
    Try to print data to debug. Commented Jul 12, 2022 at 4:40
  • I bet if you try to print the incoming data on the client side, it prints something like [object: Object] Commented Jul 12, 2022 at 4:42
  • I get that error described in the question, unexpected token o in position 1.. Commented Jul 12, 2022 at 4:43
  • If I print it on the server side with using JSON.parse I get the data object like expected. Commented Jul 12, 2022 at 4:45
  • 1
    It looks like it is a buffer. Try .toString() method on it without stringifying and log what happens. Commented Jul 12, 2022 at 4:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.