提取API,Chrome和404错误 [英] Fetch API, Chrome, and 404 Errors
问题描述
我在玩fetch
,我注意到当我获取的资源不存在(又名404)时,只有Chrome显示错误.
I'm playing around with fetch
, and I noticed that only Chrome displays an error when a resource I am fetching doesn't exist (aka a 404):
Edge和Firefox均不这样做,并且使用fetch的404错误似乎也不会触发NetworkError使我的catch错误处理程序得到通知. 如何避免在Chrome中出现此错误?
Both Edge and Firefox don't do that, and 404 errors using fetch don't seem to trigger a NetworkError to have my catch error handler to get notified. What should I do to avoid this error in Chrome?
如果您需要这样做,我的完整代码如下:
In case you need this, my full code looks as follows:
fetch("https://www.kirupa.com/book/images/learning_react2.gif", {
method: "head",
mode: "no-cors"
})
.then(function(response) {
if (response.status == 200) {
console.log("file exists!");
} else {
console.log("file doesn't exist!");
}
return response.text();
})
.catch(function(error) {
console.log("Error ", error);
});
谢谢, 基鲁巴
推荐答案
我想分享此代码段,以展示在通过API提取数据时使用promise链的另一种方法.
I would like to share this code snippet to show another way of using promise chain while fetching through an API.
<script>
let url = "https://jsonplaceholder.typicode.com/todos/1";
fetchApi(url);
function handleData(data){
console.log('succesfull:', data)
}
function fetchApi(url){
fetch(url)
.then(response => response.ok ? response.json() : Promise.reject({err: response.status}))
.then(data => handleData(data))
.catch(error => console.log('Request Failed:', error));
}
</script>
这篇关于提取API,Chrome和404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!