[英]node-fetch help - getting FetchError: invalid json response > body at <url> reason: > Unexpected end of JSON input
[英]Unexpected end of JSON input while consuming Response body (self-defined HTTP codes)
嘗試使用成功的 HTTP POST 請求的響應正文時收到以下錯誤:
SyntaxError: Unexpected end of JSON input.
這是我用來發送響應的 Express.js 語句:
res.status(204).send(response)
Express 的res.send()
方法在發送時自動將 JavaScript 對象轉換為 JSON。 無論如何, response
在其定義語句中通過JSON.stringify()
顯式轉換為 JSON。 所以我肯定會發送JSON。
--
我在客戶端上消費請求如下:
fetch(URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data) // data is defined elsewhere in the file
})
.then(res => res.json())
.then(data => console.log(data))
但是,每當我嘗試讀取response.body
以完成(請參閱Body )時,我都會收到以下錯誤:
SyntaxError: Unexpected end of JSON input.
同樣,我已經確認我希望從服務器發送到客戶端的數據是 JSON 格式。 因此,在傳輸過程中出現了問題,因為我試圖將某些東西轉換為 JSON,但實際上並不是 JSON。
我懷疑我希望發送的資源在運輸途中被放錯了地方,但我不確定如何。
兄弟,您發送的狀態碼錯誤,實際上 204 用於當一切正常時由於某種原因無法訪問內容,然后使用 200 狀態碼。
res.status(200).send(response);
評論后更新答案。
res.status(400).json({
code : 400,
message: "error message string"
})
問題是我將我的狀態代碼自定義為 204。
指定 HTTP 狀態204
時,僅轉發請求的標頭。 不會轉發任何正文內容。
回想一下,我最初的 Express 回復是:
res.status(204).send(response)
通過定義 HTTP status 204
,我確保send(response)
response
的響應將被丟棄。
我的問題通過更新我的回復得到解決:
res.send(response)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.