javascript – 获取API,Chrome和404错误

我正在玩fetch,我注意到当我提取的资源不存在时,只有Chrome显示错误(也就是404):

《javascript – 获取API,Chrome和404错误》

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

谢谢,
Kirupa

最佳答案

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>

index.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");
    });
}());

开发工具截图

《javascript – 获取API,Chrome和404错误》

火狐

《javascript – 获取API,Chrome和404错误》

苹果浏览器

《javascript – 获取API,Chrome和404错误》

分析

浏览器知道资源是否存在的唯一方法是实际发出网络请求. Chrome始终会记录404之类的网络请求错误.这就是为什么当您访问的网站没有关于favicon时,您可能会看到很多关于favicons的错误.

您无法强制您的客户端使用您自己的代码看不到它们,但用户可以通过更改自己的浏览器设置来选择让错误显示给他们.见this answer to Suppress Chrome ‘Failed to load resource’ messages in console.

点赞