簡體   English   中英

使用 fetch 獲取 API 響應負載

[英]Getting API response payload using fetch

我正在使用 fetch 來獲取 API 對 GET 和 POST 請求的響應。 發生錯誤時,我可以看到狀態代碼和文本,即 400 Bad Request。 但是,傳遞的附加信息解釋了引發錯誤的原因(即用戶名不匹配)。 我可以通過 Firefox 開發人員工具的控制台在響應負載中看到這條附加消息,但我不確定如何通過處理獲取響應來獲取它。

這是一個示例請求:

fetch(url, {
  method: 'POST',
  body: JSON.stringify({
    name: name,
    description: description
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
    "Authorization": "Bearer " + token
  }
}).then(response => {
  if (!response.ok) {
    throw Error(response.statusText)

  }
  return response
})
.catch(error => {
  console.log(error)
})

有任何想法嗎? 謝謝。

您似乎只傳遞了響應的statusText字段,它對應於 HTTP 狀態代碼(而不是響應正文) - 例如Bad Request for HTTP 響應代碼400

您可以使用獲取 API 返回的響應 object 上定義的方法之一來讀取響應正文。 例如,如果您期待 JSON 響應正文,您可以:

const onSuccess = response => {
  // Do something with the response
  // What you return from here will go to the next .then
}

const onFailure = response => {
  // response.json() returns a promise that resolves to the JSON sent in the body
  // Note that whatever is returned from here will go to the next .then
  // To go to the next .catch, you can throw from here
  return response.json().then(jsonResponse => console.log(jsonResponse))
}

fetch(url, {
  method: 'POST',
  body: JSON.stringify({
    name: name,
    description: description
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
    "Authorization": "Bearer " + token
  }
}).then(response => {
  if (!response.ok) {
    throw response
  }
  return response
})
.then(onSuccess, onFailure)
.catch(err => { /* Any error thrown from the handlers will be caught here */ })

您可以查看響應 object 文檔以了解更多詳細信息。

謝謝大家的建議。

本教程幫助我了解該怎么做。

https://css-tricks.com/using-fetch/

我的問題是,當出現錯誤時,響應不是 JSON,而是文本。 所以我需要做這樣的事情(取自 css-tricks.com):

fetch('https://api.github.com/users/chriscoyier/repos')
.then(response => response.text())
  .then(data => {
    console.log(data)
  });

根據文檔,我會按照以下方式做更多的事情:

const response = await fetch('http://example.com/movies.json')
const myJson = await response.json();
console.log(JSON.stringify(myJson));

否則,您必須在.then()內完成所有操作。

關於您要查找的附加文本,這完全取決於響應 object,而且我沒有看到它就無法知道。

@Voxum,您的答案缺少重要信息,例如方法..and ; await 很好,但請記住它應該在異步 function 中,如果您“thenify”.then .then()則不需要使用它,因為它返回 promise。 來自 Fetch 文檔,這是他們的基本 get/HTML 示例。 我認為 OP 要求 API 調用不同類型的方法,這將需要更高級的設置。

問題是 400 響應,服務器沒有給您響應消息,因為 404(例如)告訴您找不到頁面。 通常服務器會給你一個響應消息的唯一時間是你得到一個好的(成功/200)。 response.json() 或 response.text() 通常會有一條消息,具體取決於您返回的數據。

使用 url 調用 fetch 后,方法和任何標頭使用.then((response) => {console.log(response.json());}); 對於 json 並使用 .then .then((response) => {console.log(response.text());}); 對於 xml/文本

OP 正確設置了 fetch,但只需要使用response.json()response.text() 同樣,200 響應仍然可能是“密碼錯誤”,這就是您將使用它的地方。 不要指望 400/500 上有響應機構。 祝你好運!

暫無
暫無

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

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