Fetch API, Chrome, and 404 Errors

Viewed 10915

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): enter image description here

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

Thanks, Kirupa

4 Answers

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>
Related