Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Responses other than 200 OK From Fetch

I'm using the native fetch library as specified here. It seems that whenever a response other than a 200 OK is returned it throws an exception with the string response Uncaught (in promise) TypeError: Failed to fetch.

Was there a way to catch and branch on specific HTTP response codes and still view the response data? For example a 401 response?

I have attached my request code I am using as a wrapper for fetch.

static request(url, data) {

    let headers = {
        "Authorization": window.localStorage.getItem("Authorization"),
        "Content-Type": "application/json"
    };

    let options = {
        method: "GET",
        headers: headers,
        mode: "no-cors",
        cache: "no-cache",
    };

    if (data) {
        options = {
            method: "POST",
            headers: headers,
            mode: "no-cors",
            cache: "no-cache",
            body: JSON.stringify(data)
        }
    }

    return new Promise(async (resolve, reject) => {

        try {

            let response = await fetch(url, options);
            let jsonResponse = await response.json();
            return resolve(jsonResponse);

        } catch (error) {
            // hashHistory.push("/login");
            return reject(error);
        }

    })

}   
like image 853
James Marino Avatar asked Jul 11 '17 01:07

James Marino


People also ask

How do I get responses from Fetch?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do you check if fetch was successful?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

What are disadvantages of fetch API?

XHR limitations and drawbacks: more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.

What errors does fetch catch?

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response. ok property to see if the request failed and reject the promise ourselves by calling return Promise.


2 Answers

"An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this (https://developer.mozilla.org/pt-BR/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful):

fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    response.blob().then(function(myBlob) {
      var objectURL = URL.createObjectURL(myBlob);
      myImage.src = objectURL;
    });
  } else {
    console.log('Network response was not ok.');
  }
})
.catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
});

"

like image 146
Henrique Oecksler Bertoldi Avatar answered Sep 30 '22 04:09

Henrique Oecksler Bertoldi


You can check Response Headers .status property, .text() to read Response. If Response is expected to be read more than once, you can use .clone()

let request = fetch("/path/to/resource");

request
.then(response => {

    const status = response.headers.get("status");

    console.log(status);

    if (status == 401) {
      // read 401 response
      response.text().then(res = > console.log(res));
      return "404.html"
    }
    if (status == 200) {
      return "200.html"
    }
})
.then(result => console.log(result))
.catch(err => // handle error);
like image 34
guest271314 Avatar answered Sep 30 '22 06:09

guest271314