Uncaught SyntaxError: Unexpected Token o in JSON


#1

I am getting an error when using the code from Chapter 17. The error is as follows:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at WebSocket.socket.onmessage (app\scripts\src\ws-client.js:18)

It seems to be related to this line: let data = JSON.parse(e.data) in the registerMessageHandler function. According to the book, e.data is a json string and each time “you” receive it “you” convert it to a JavaScript object which is what JSON.parse(e.data) is supposed to be doing. However, in googling the error I’m getting, the responses indicate that this error occurs when using JSON.parse on something that is already a JavaScript object. so is the line with the JSON.parse call not necessary? I’m quite confused here.


#2

Do you still have your chatbot automatically sending an introductory message (which, if left over from the previous chapter, is not in JSON format)?


#3

Had a similar issue. Check your websockets-server.js file for the section below. I was sending an additional value in the “clientSocket.send(data);” line to show which client window the data was coming from. This causes a json parsing error since it wasn’t correct json. Once removed, no issue.

  socket.on('message', function (data) {
    console.log('message received: ' + data);
    messages.push(data);
    var clientCount = 0;
    ws.clients.forEach(function(clientSocket){
      clientSocket.send(data);
    });
  });