使用 fetch 获取 API 响应负载

Getting API response payload using fetch

我正在使用 fetch 获取 GET 和 POST 请求的 API 响应。发生错误时,我能够看到状态代码和文本,即 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)
})

有什么想法吗?谢谢

根据文档,我会按照以下方式做更多的事情:

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

否则你必须在 .then().

中完成所有操作

关于您要查找的附加文本,这完全取决于响应对象,我没有看到就无法知道。

@Voxum,您的答案缺少重要信息,例如方法..; await 很好,但请记住它应该在异步函数中,如果您 "thenify" .then() 就像那个 returns 的承诺。来自 Fetch 文档,这是他们的基本 get/HTML 示例。我认为 OP 要求 API 调用不同类型的方法,这将需要更高级的设置。

问题是 400 响应,服务器没有给您响应消息,因为 404(例如)告诉您找不到该页面。通常只有当你得到一个好的(success/200)时,服务器才会给你一个响应消息。根据您返回的数据,通常会在 response.json() 或 response.text() 处显示一条消息。

在使用 url 方法和任何 headers 方法调用 fetch 之后 .then((response) => {console.log(response.json());}); 用于 json 并使用 .then((response) => {console.log(response.text());}); 对于 xml/text

OP 已正确设置提取,但只需要使用 response.json()response.text()。同样,200 响应仍然可以是 "incorrect password",这就是您要使用它的地方。不要指望在 400/500 上得到响应 body。祝你好运!

您似乎只传递了响应的 statusText 字段,它对应于 HTTP 状态代码 (而不是响应正文) - 例如 Bad Request 用于 HTTP 响应代码 400.

您可以使用在提取返回的 Response 对象上定义的方法之一来读取响应正文 API。例如,如果您期望 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 */ })

您可以查看 Response object documentation 了解更多详情。

谢谢大家的建议。

本教程帮助我了解了该做什么。

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