Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda