小编dmr*_*tix的帖子

使用 fetch 获取 API 响应负载

我使用 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)
})
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

javascript response fetch-api

2
推荐指数
1
解决办法
8237
查看次数

标签 统计

fetch-api ×1

javascript ×1

response ×1