从 Fetch 中捕获 200 OK 以外的响应

Jam*_*ino 4 javascript http fetch-api ecmascript-2017

我正在使用此处指定的本机提取库。似乎每当返回 200 OK 以外的响应时,它都会引发字符串 response 异常Uncaught (in promise) TypeError: Failed to fetch

有没有办法在特定的 HTTP 响应代码上捕获和分支并仍然查看响应数据?例如 401 响应?

我附上了我用作获取包装器的请求代码。

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

    })

}   
Run Code Online (Sandbox Code Playgroud)

Hen*_*ldi 5

“对成功 fetch() 的准确检查将包括检查 promise 是否已解决,然后检查 Response.ok 属性的值是否为 true。代码看起来像这样(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);
});
Run Code Online (Sandbox Code Playgroud)