javascript – 使用反馈JS中的fetch处理响应状态
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用反馈JS中的fetch处理响应状态,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2123字,纯文字阅读大概需要4分钟。
内容图文
我刚开始学习ReactJS.现在,我想知道在使用fetch发出API请求时如何处理响应状态.这是我的代码:
componentDidMount(){
this.setState({ isLoading: true })
var id = this.props.match.params.id
const api = `bla/bla/${id}`;
console.log("start call api")
fetch(api)
.then((response) => {
if(response.status === 200){
console.log("SUCCESSS")
return response.json();
}else if(response.status === 408){
console.log("SOMETHING WENT WRONG")
this.setState({ requestFailed: true })
}
})
.then((data) => {
this.setState({ isLoading: false, downlines: data.response })
console.log("DATA STORED")
})
.catch((error) => {
this.setState({ requestFailed: true })
})
console.log("end call api")
}
我关闭了我的连接以进行408的测试,但我的加载仍然出现.
render(){
const { isLoading, requestFailed } = this.state;
if(requestFailed){
return(
<div className="errorContainer">
<a className="errorMessage">Opss.. Something went wrong :(</a>
</div>
)
}
}
有什么想法解决这个问题?
解决方法:
根据MDN文档:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this:
fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ',
error.message);
});
查看您的代码,我认为您的408错误检查不会运行.我认为事实并非如此.基本上上面的代码正在做的是如果请求是200的确定则返回json响应,否则它会抛出错误.如果发生错误,那么你的第二个错误就永远不会运行,它会被抛到catch块.也许你可以设置isLoading:false吗?
你也是api结束的日志声明不正确.这是在你的承诺完成之前被调用的.
内容总结
以上是互联网集市为您收集整理的javascript – 使用反馈JS中的fetch处理响应状态全部内容,希望文章能够帮你解决javascript – 使用反馈JS中的fetch处理响应状态所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。