簡體   English   中英

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

[英]Unexpected token u in JSON at position 1

我知道這是一個常見的問題,但是在獲取數據時卻不斷出現此錯誤:

SyntaxError:JSON中意外的令牌u在JSON.parse()的位置1

這是在我測試完整代碼時發生的,因此我使用

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

在我的客戶端,我正在使用以下代碼:

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

測試這些值時,服務器端的所有內容都會打印正確的值。 但是,當我使用console.log在客戶端打印出responseText時,我得到了:

f text(){[本地代碼]}

為什么調用此錯誤? 通過環顧堆棧溢出,我了解到當我嘗試解析未定義的字符串時會發生此錯誤。 我在解析之前放置了一個if語句來檢查字符串是否未定義:

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

但是它沒有輸出,所以字符串真的不確定嗎? 附帶說明,節點是最新的。 感謝您的幫助。如果在另一個問題中回答了此問題,請告訴我。 我尚未找到解決此問題的方法。

編輯:

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));
    }
}

編輯:response.text應該是response.text()。 這給了我我的錯誤。

更新以匹配新的問題代碼

一個承諾鏈使用上一個的返回值來解析每個新的承諾。

您應該注意, fetch() API返回帶有Response對象的Promise解析。 它沒有text 屬性 ,因此checkStatus使用undefined解析(因此錯誤消息中為“ u”)。

我建議您使用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}`))
})

對於fetch() ...

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

在服務器端,您可能要使用res.json()而不是手動對數據進行字符串化

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM