Kir*_*mbi 5 javascript google-chrome fetch-api
我在玩fetch,并且注意到当我获取的资源不存在(又名404)时,只有Chrome显示错误:

Edge和Firefox都不这样做,并且使用fetch的404错误似乎也不会触发NetworkError使我的catch错误处理程序得到通知。我应该怎么做才能避免Chrome中出现此错误?
如果您需要它,我的完整代码如下所示:
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);
});
Run Code Online (Sandbox Code Playgroud)
谢谢,基鲁帕
当我获取的资源不存在时,只有 Chrome 会显示错误(也称为 404)
我在 Firefox、Chrome 和 Safari 中将此视为错误。
我尝试使用以下运行来复制您所说的内容http-server。没有“data.json”文件。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Async Test</title>
<script src="index.js"></script>
</head>
<body>
<main>
<h1>Async Test</h1>
</main>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
(async function() {
let a;
try {
a = await fetch("./data.json", {
method: "head"
});
console.log("No error");
} catch (err) {
console.log("Caught an error");
}
console.log(a);
}());
(function() {
fetch("./data.json", {
method: "head"
})
.then(data => {
console.log("No error");
console.log(data);
})
.catch(err => {
console.log("Caught an error");
});
}());
Run Code Online (Sandbox Code Playgroud)
浏览器知道资源是否存在的唯一方法是实际发出网络请求。Chrome 总是记录网络请求错误,例如404。这就是为什么当您访问的网站没有网站图标时,您可能会看到很多有关网站图标的错误。
您不能强迫您的客户不使用您自己的代码看到它们,但用户可以选择通过更改自己的浏览器设置来不向他们显示错误。请参阅Suppress Chrome 'Failed to load resources' messages in console 的答案。
小智 -2
您可以尝试在 Promise 被拒绝时调用的 pass 函数。您可以通过传递第二个函数来做到这一点then
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
| 归档时间: |
|
| 查看次数: |
3654 次 |
| 最近记录: |