从 Fetch 捕获 200 OK 以外的响应

问题描述 投票:0回答:2

我正在使用此处指定的本机获取库。似乎每当返回 200 OK 以外的响应时,它都会抛出字符串响应

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

    })

}   
javascript http fetch-api ecmascript-2017
2个回答
8
投票

“对成功 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);
});


2
投票

您可以检查

Response
Headers
.status
属性,
.text()
来读取
Response
。如果
Response
预计会被多次读取,您可以使用
.clone()

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

request
.then(response => {
   
    const status = response.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);
© www.soinside.com 2019 - 2024. All rights reserved.