使用$fetch Javascript处理HTTP Ajax调用中的错误
我试图在HTTP ajax调用中处理与网络相关的问题。因此,我暂时停止了IIS中相应API的服务,并尝试调用关闭的API-使用$fetch Javascript处理HTTP Ajax调用中的错误,javascript,reactjs,fetch-api,Javascript,Reactjs,Fetch Api,我试图在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) {
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块,没有触发任何警报,并且抛出了一个错误。此外,response.json()代码>在成功块中,我不知道它是如何执行的
TypeError: response.json is not a function
Stack trace:
onFetchError/<@http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13
TypeError:response.json不是函数
堆栈跟踪:
onFetchError/基于,您可以尝试在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
}
});
您是否在所有这些if语句之前记录了响应?api不显示response.status
,而是显示response.ok
。status看起来更像是一个XMLHttpRequest对象propOh,这与jQuery无关,fetch是一个本机的JS实验性XHR函数,它失败了。。。当前,它会触发HTTP选项
,如果请求服务器脱机,它不会将任何响应返回到浏览器。我在我的问题中公布了一个细节