从Fetch中捕获200以外的响应

时间:2017-07-11 01:48:46

标签: javascript http fetch-api ecmascript-2017

我正在使用指定here的本机提取库。似乎只要返回200 OK以外的响应,它就会抛出字符串响应Uncaught (in promise) TypeError: Failed to fetch的异常。

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

我附上了我正在使用的请求代码作为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);
        }

    })

}   

2 个答案:

答案 0 :(得分:1)

“准确检查成功获取()将包括检查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);
});

答案 1 :(得分:1)

您可以查看$credit = DB::table('table') ->selectRaw(' Total AS Total, SUM(Hours) AS Hours, SUM(Charge) AS Charge, NULL AS Paid ') ->where('type', '=', 'credit') ->groupBy('id'); $tax = DB::table('table') ->selectRaw(' Total AS Total, SUM(Hours) AS Hours, SUM(Charge) AS Charge, NULL AS Paid ') ->where('type', '=', 'tax') ->groupBy('id'); $all = DB::table('table') ->selectRaw(' Total AS Total, SUM(Hours) AS Hours, SUM(Charge) AS Charge, NULL AS Paid ') ->where('type', '=', 'regular') ->groupBy('id') ->union($credit) ->union($tax); $totals = DB::selectRaw(' Total, SUM(Hours), SUM(Charge), Paid ') ->from( $all->toSql() ) ->groupBy('Total') ->get(); Response Headers媒体资源,.status阅读.text()。如果预计Response被多次阅读,您可以使用Response

.clone()