Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Returning a JSON array object from the server side in a JavaScript web socket

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);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!