dmr*_*tix 2 javascript response 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)
有任何想法吗?
谢谢大家的建议。
本教程帮助我了解了该怎么做。
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)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8237 次 |
| 最近记录: |