简体   繁体   English

JSON中位置1处的意外令牌u

[英]Unexpected token u in JSON at position 1

I know this is common question, but I keep getting this error when fetching data: 我知道这是一个常见的问题,但是在获取数据时却不断出现此错误:

SyntaxError: Unexpected token u in JSON at position 1 at JSON.parse () SyntaxError:JSON中意外的令牌u在JSON.parse()的位置1

This happened when I testing my full code, so I made tested with 这是在我测试完整代码时发生的,因此我使用

res.send(JSON.stringify({"data": "test"}));

In my client side, I'm using this code: 在我的客户端,我正在使用以下代码:

fetch(url)                                   // fetch works
    .then(checkStatus)                       // checks for errors, if none send response text
    .then(function (responseText) {
        let data = JSON.parse(responseText); // where I'm getting the error

When testing the values, everything in my server side prints the correct values. 测试这些值时,服务器端的所有内容都会打印正确的值。 However, when I use console.log to print out the responseText on the client side, I get this: 但是,当我使用console.log在客户端打印出responseText时,我得到了:

f text() { [native code] } f text(){[本地代码]}

Why is this error being called? 为什么调用此错误? From looking around stack overflow, I understand that this error happens when I attempt to parse a string that's undefined. 通过环顾堆栈溢出,我了解到当我尝试解析未定义的字符串时会发生此错误。 I put an if statement before the parse to check is the string is undefined: 我在解析之前放置了一个if语句来检查字符串是否未定义:

if (responseText === undefined) {
    console.log("responseText is undefined");
}

But it didn't output, so is the string really undefined? 但是它没有输出,所以字符串真的不确定吗? As a side note, node is up to date. 附带说明,节点是最新的。 Thank you for helping.If this is answered in another question, please let me know. 感谢您的帮助。如果在另一个问题中回答了此问题,请告诉我。 I haven't found a solution to this problem. 我尚未找到解决此问题的方法。

Edit: 编辑:

function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response.text;
    } else if (response.status === 404) {
        clear();
        return Promise.reject(new Error("Sorry, we couldn't find that page"));
    } else {
        console.log(response.text());
        return Promise.reject(new Error(response.status + ": " + response.statusText));
    }
}

Edit: response.text is supposed to be response.text(). 编辑:response.text应该是response.text()。 This gave me my error. 这给了我我的错误。

Updated to match new question code 更新以匹配新的问题代码

A promise chain resolves each new promise with the return value from the last. 一个承诺链使用上一个的返回值来解析每个新的承诺。

You should note the fetch() API returns a Promise resolving with a Response object. 您应该注意, fetch() API返回带有Response对象的Promise解析。 This does not have a text property , so checkStatus is resolving with undefined (hence the "u" in the error message). 它没有text 属性 ,因此checkStatus使用undefined解析(因此错误消息中为“ u”)。

I suggest you use the Body.json() method to parse the JSON response, ie change checkStatus to use 我建议您使用Body.json()方法来解析JSON响应,即将checkStatus更改为

if (res.ok) { // same as checking status between [200, 300)
  return res.json()
}
if (res.status === 404) {
  clear()
  return Promise.reject(new Error("Sorry, we couldn't find that page"))
}
// text(), like json() returns a promise
return res.text().then(responseText => {
  console.error(responseText)
  return Promise.reject(new Error(`${res.status}: ${res.statusText}`))
})

and for fetch() ... 对于fetch() ...

fetch(url)
  .then(checkStatus)
  .then(data => {
    // data is already parsed into an object
  })

On the server-side, you might want to use res.json() instead of manually stringifying your data 在服务器端,您可能要使用res.json()而不是手动对数据进行字符串化

res.json({ data: 'test' })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM