gpt4 book ai didi

javascript fetch 无法捕获 404 错误

转载 作者:行者123 更新时间:2023-12-03 01:18:25 25 4
gpt4 key购买 nike

我有一个应用程序,使用 fetch 从第 3 方 API 检索信息。我通过 cors-anywhere-herokuapp.com 调用 API。当我使用有效数据调用 API 时,我能够检索 API 响应并获取我需要获取的数据。当我使用无效数据调用 API 时,API 返回 404 服务器错误。我强制输入无效数据,以便我可以编写代码来捕获这种情况。我的问题似乎是 fetch 没有捕获 404 错误。我尝试编码来检查 return.status 但无济于事。我尝试测试 return.ok 但也不起作用。这是我正在执行的代码:

            function showProduct(barcode) {

let url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=" + barcode + "&key=mj1pm32ylcctxj1byaia85n9dk2d4i";

url = "https://cors-anywhere.herokuapp.com/http://api.barcodelookup.com/v2/products?barcode=5000159459211&key=mj1pm32ylcctxj1byaia85n9dk2d4i";

const options = { method: 'GET' };
fetch( url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
console.log("fetch failed")
}
else
{
//inspect the data that the WebAPI returned
document.getElementById("showScanner").style.visibility = "hidden";
document.getElementById("scanner-container").style.visibility = "hidden";
document.getElementById("showProductDiv").style.visibility = "visible";
document.getElementById("productManufacturer").innerHTML = myJson.products[0].manufacturer;
document.getElementById("productName").innerHTML = myJson.products[0].product_name;
document.getElementById("productDescription").innerHTML = myJson.products[0].description;
Quagga.stop();
}
});
}

这是我执行代码时在调试器中看到的内容

enter image description here

当我查看调试器网络选项卡并单击“ header ”时,我看到以下内容: enter image description here

所以,我的问题是,如何捕获状态代码?

最佳答案

根据the documentation on fetch's response ,您应该能够使用 response.status 测试 fetch 的 Promise 解析的响应的状态代码。

请注意,虽然不直观,但 Promise fetch 仅在出现连接错误时返回拒绝。如果连接成功并且有响应,则即使状态代码不是 200,此 promise 也将随响应一起解析。

关于javascript fetch 无法捕获 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51887680/

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