使用$ fetch Javascript进行HTTP Ajax调用时的错误处理
问题描述:
我试图处理HTTP ajax调用中的网络相关问题。因此,我暂时停止了IIS中各自的API服务,并试图调用关闭的API - http://localhost:1000/GetData
。
fetch("http://localhost:1000/GetData")
.then(handleErrors)
.then(function(response) {
return response.Json();
}).catch(function(error) {
console.log(error);
});
我尝试下面的代码太
fetch("http://localhost:1000/GetData")
.then(response => {
if(response) {
if (response.status === 200) {
alert('Super');
return response.json();
} else {
alert('Hai');
return '';
}
} else {
alert('Oooops');
return '';
}
})
.catch(function(error) {
console.log(error);
});
但它的失败,直接击中catch块,而不会触发任何alert
及其引发错误。而且response.json();
在成功块,我不知道它是如何执行的。
TypeError: response.json is not a function
Stack trace:
onFetchError/<@http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13
请帮助我如何检查状态码,以及如何处理网络错误(即网络不可用404,等)
答
基于this issue on Github,您可以尝试识别catch块中的错误类型。所以,类似这样的东西可能适用于您的情况:
fetch("http://localhost:1000/GetData")
.then(response => {
alert("Super");
return response.json();
})
.catch(err => {
const errStatus = err.response ? err.response.status : 500;
if (errStatus === 404){
// do something
} else {
// do another thing
}
});
+1
它的失败......目前它触发'HTTP OPTIONS',它不返回任何响应如果请求服务器处于脱机状态,则返回浏览器。我在我的问题中发布了详细信息https://stackoverflow.com/questions/45182002/handling-of-failure-status-in-http-options-ajax-call – 2017-07-19 05:57:36
您是否在所有这些if语句之前控制台记录了响应? –
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch api不显示'response.status',而是显示'response.ok'。 .status似乎更像是一个XMLHttpRequest对象prop –
呵呵,这根本不是jQuery相关的,fetch是一个原生的JS实验性XHR函数 –