javascript - Fetch API、Chrome 和 404 错误

标签 javascript google-chrome fetch-api

<分区>

我正在尝试使用 fetch,我注意到当我正在获取的资源不存在时,只有 Chrome 会显示错误(又名 404): enter image description here

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

Chrome Dev Tools

火狐

Firefox Dev Tools

Safari

Safari Dev Tools

分析

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

您不能用您自己的代码强制您的客户看不到它们,但是用户可以通过更改他们自己的浏览器设置来选择不向他们显示错误。参见 this answer to Suppress Chrome 'Failed to load resource' messages in console .

关于javascript - Fetch API、Chrome 和 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019776/

相关文章:

javascript - 当 http 响应状态为 400 时使用 fetch api 获取自定义错误消息

javascript - 将 &lt;input type ="time"> 值(作为持续时间)转换为 JS/PHP 小时 float

javascript - 先按字母排序,再按数字排序

css - Chrome 对 margin-top 的解释与 Firefox 不同

javascript - 将 setInterval 与 requestAnimationFrame 一起使用

JavaScript 检查资源是否可以通过 fetch 访问

javascript - Asp mvc 和 Ajax 中的自动完成

javascript - 当创建多个 onmouseover 事件时,它们将 "overwriting"保留为前一个,直到代码仅识别最后一个事件

css - Webkit 错误?损坏的 CSS

javascript - 如何使用 JS fetch API 上传文件?