标签:class col resolve asi www. ast 扩展性 lang round
前言:ant-design-pro的技术组成主要是react+redux+dva+antd+fetch+roadhog,dva在源码包index.js里面导出了fetch,但是如果不想使用fetch库,想换成其他库也是可以的(axios后期扩展性更好些),roadhog主要是基于webpack实现的封装。关于fetch发送请求的代码都封装在了utils/request.js文件中。PS:这里重点梳理对fetch()的使用学习,原文地址:大灰狼的小棉羊哥哥博客
function reqListener(){
var data=JSON.parse(this.responseText);
console.log(data);
}
function reqError(err){
console.log("Fetch错误:"+err);
}
var oReq=new XMLHttpRequest();
oReq.onload=reqListener;
oReq.onerror=reqError;
oReq.open("get","/students.json",true);
oReq.send();
fetch("/students.json")
.then(
function(response){
if(response.status!==200){
console.log("存在一个问题,状态码为:"+response.status);
return;
}
//检查响应文本
response.json().then(function(data){
console.log(data);
});
}
)
.catch(function(err){
console.log("Fetch错误:"+err);
});
fetch("/students.json")
.then(
function(response){
console.log(response.headers.get(‘Content-Type‘));
console.log(response.headers.get(‘Date‘));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
}
)
fetch("http://www.html5online.com.cn/cors-enabled/students.json",{mode:"cors"})
.then(
function(response){
console.log(response.headers.get(‘Content-Type‘));
console.log(response.headers.get(‘Date‘));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
}
)
.catch(function(err){
console.log("Fetch错误:"+err);
});
function status(response){
if(response.status>=200 && response.status<300){
return Promise.resolve(response);
}
else{
return Promise.reject(new Error(response.statusText));
}
}
function json(response){
return response.json();
}
fetch("/students.json")
.then(status)
.then(json)
.then(function(data){
console.log("请求成功,JSON解析后的响应数据为:",data);
})
.catch(function(err){
console.log("Fetch错误:"+err);
});
在上述代码中,我们定义了status函数,该函数检查响应的状态码并返回Promise.resolve()方法或Promise.reject()方法的返回结果(分别为具有肯定结果的Promise及具有否定结果的Promise)。这是fetch()方法链中的第一个方法。如果返回肯定结果,我们调用json()函数,该函数返回来自于response.json()方法的Promise对象。在此之后我们得到了一个被解析过的JSON对象,如果解析失败Promise将返回否定结果,导致catch段代码被执行。
这样书写的好处在于你可以共享fetch请求的逻辑,代码容易阅读、维护及测试。
fetch(url,{
method:"post",
headers:{
"Content-type":"application:/x-www-form-urlencoded:charset=UTF-8"
},
body:"name=lulingniu&age=40"
})
.then(status)
.then(json)
.then(function(data){
console.log("请求成功,JSON解析后的响应数据为:",data);
})
.catch(function(err){
console.log("Fetch错误:"+err);
});
fetch(url,{
credentials:"include"
})
pro约定了当状态码200~300为网络请求成功状态,其余均为失败状态。

其次,pro对delete方法以及网络状态为204时自动做了text()方法,在校验delete方法时,要注意json.parse()后进行校验,并且谨慎使用204的网络状态。


资料来源:ryzZZ简书
标签:class col resolve asi www. ast 扩展性 lang round
原文地址:https://www.cnblogs.com/ljq66/p/10676902.html