gpt4 book ai didi

javascript - 使用 fetch 获取 API 响应负载

转载 作者:行者123 更新时间:2023-12-02 00:13:08 25 4
gpt4 key购买 nike

我正在使用 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)
})

有什么想法吗?谢谢。

最佳答案

谢谢大家的建议。

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

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

关于javascript - 使用 fetch 获取 API 响应负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58208690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com