"Uncaught SyntaxError: Unexpected token l in JSON at position 0", but still works, why?

huangapple go评论80阅读模式
英文:

"Uncaught SyntaxError: Unexpected token l in JSON at position 0", but still works, why?

问题

第一次使用Go的Websockets,并且遇到了一个奇怪的错误,它并没有中断程序的执行,仍然继续执行,就好像没有问题一样。客户端是一个ReactJS单页应用程序。

JS客户端:

const socket = new WebSocket("ws://localhost:5000/ws");
setConnection(socket);

socket.onmessage = (e) => {
    const message = JSON.parse(e.data);
    console.log("message:", message);

    switch (message.Command) {
        case "loginResult":
            if (message.Result) {
                console.log("login worked");
            } else {
                console.log("login did not work");
            }
            break;
    }
}

Go代码片段中获取JSON的部分:

result := ws.LoginResult{
    BaseMessage: ws.BaseMessage{
        Command: "loginResult",
    },
    Result: false,
}

b, err := json.Marshal(result)

if err != nil {
    fmt.Println(err)
    return
}

if err = conn.WriteMessage(msgType, b); err != nil {
    return
}

输出结果:

in here
WebsocketProvider.tsx:20 message: {Command: 'loginResult', Result: false}
WebsocketProvider.tsx:27 login did not work
VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (<anonymous>)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

有人知道为什么会出现这种情况吗?

问题已找到解决方法:

  • 这与代码迁移有关,一个残留的代码行导致了一个被忽略的调用,因此对执行没有任何影响。这与JSON格式不同无关,因为这是由Go库自动生成的。
英文:

First time using websockets with Go and getting a weird error that doesn't break the program, and still continue as if it was not a problem. The client is a ReactJS single page application.

JS Client:

 const socket = new WebSocket(&quot;ws://localhost:5000/ws&quot;);
            setConnection(socket);

            socket.onmessage = (e) =&gt; {
                const message = JSON.parse(e.data)
                console.log(&quot;message:&quot;, message)
          
                switch (message.Command) {
                  case &quot;loginResult&quot;:
                    if (message.Result) {
                      console.log(&quot;login worked&quot;);
                    }else{
                      console.log(&quot;login did not work&quot;);
                    }
                    break;
                }
              }

Snippet of Go it is getting JSON from:

result := ws.LoginResult{
		BaseMessage: ws.BaseMessage{
			Command: &quot;loginResult&quot;,
		},
		Result: false,
	}

b, err := json.Marshal(result)

if err != nil {
	fmt.Println(err)
	return
}

if err = conn.WriteMessage(msgType, b); err != nil {
	return
}

And the output:

in here
WebsocketProvider.tsx:20 message: {Command: &#39;loginResult&#39;, Result: false}
WebsocketProvider.tsx:27 login did not work
VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (&lt;anonymous&gt;)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

Anyone have any idea why this is the case?

Solution was found:

  • It was to do with the migration of code and that a left over line was making a call that was ignored, hence where it made no difference to the execution. Nothing to do with the JSON format being difference since this was automatically generate by Go libraries.

答案1

得分: 1

你编写的onmessage函数将在每次接收到有效的WebSocket消息时运行

根据你发布的调试日志,当你从服务器接收到有效的JSON并且函数成功运行完成时,工作的部分是这行代码:

WebsocketProvider.tsx:27 login did not work

请标记行号。

之后你得到了以下内容:

VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (&lt;anonymous&gt;)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

请标记行号:19
这是你的JSON.parse所在的行。

我猜测这是一条新的无效的JSON消息,它确实在这里出现了错误,并且函数的其余部分没有运行——已经运行的部分是之前的一条带有有效JSON的消息。

至于为什么失败了——按照@emptyhua的建议,在你的JSON.parse之前加入一个console.log,以查看你到底接收到了什么。

英文:

the function you have written for onmessage will be run every time a valid websocket message has been received.

According to the debug log you have posted the bit that worked was when you did receive valid JSON from the server and the function ran to completion as evidenced by this line:

WebsocketProvider.tsx:27 login did not work

Mark the line number.

After this you get:

VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (&lt;anonymous&gt;)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

mark the line number :19
This is the line with your JSON.parse.

My guess would be that this is a new invalid json message and it did indeed panic here and the rest of the function did not run - the bit that ran was a previous message with valid json.

As for why it failed - put in a console.log before your JSON.parse as suggested by @emptyhua to see what exactly you are receiving.

huangapple
  • 本文由 发表于 2021年10月21日 21:35:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69662991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定