我正在尝试使用 fetch
,我注意到当我正在获取的资源不存在时,只有 Chrome 会显示错误(又名 404):
Edge 和 Firefox 都不会这样做,使用 fetch 的 404 错误似乎不会触发 NetworkError 让我的捕获错误处理程序得到通知。 我应该怎么做才能避免在 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);
});
谢谢,
基鲁巴
only Chrome displays an error when a resource I am fetching doesn't
exist (aka a 404)
我在 Firefox、Chrome 和 Safari 中看到这是一个错误。
我正在使用的代码
我尝试使用以下与 http-server
一起运行来复制您所说的内容.没有“data.json”文件。
index.html
<!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>
索引.js
(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");
});
}());
开发工具截图
Chrome
火狐
Safari
分析
浏览器要知道资源是否存在的唯一方法就是实际发起网络请求。 Chrome 始终记录网络请求错误,例如 404。这就是为什么当您访问的网站没有图标时,您可能会看到很多关于图标的错误。
您不能用您自己的代码强制您的客户看不到它们,但是用户可以通过更改他们自己的浏览器设置来选择不向他们显示错误。参见 this answer to Suppress Chrome 'Failed to load resource' messages in console .