fetch的相关概念以及二次封装(与axios二次封装道理类似)
1、fetch:
①fetch是window下面的一个方法;
②脱离了XHR,是ES的规范;
③兼容性不太好
④基于promise的API
2、安装:cnpm install whatwg-fetch -S
3、GET请求:(默认)
fetch(url+?key=val,{
headers:请求头
method:请求方式
})
4、POST:
fetch(url,{
headers:请求头
method:请求方式
body:post传递参数的属性
})
5、特点:
不管是get还是post请求,当请求成功之后,第一个.then中是一个未处理的结果集;
第二个.then中才是最后的结果(也就是我们想要得到的结果);fetch默认是不会携带cookie的,
如果想要携带cookie,需要设置credentials:"include"
6、
fetch(url) .then((res)=>{结果集的处理}) .then((data)=>{ console.log(data); }) 结果集的处理:你想要的数据格式是哪种格式 text json blob formData
7、fetch的二次封装,可配合async,await使用
import {fetch as fetchPro} from "whatwg-fetch";
import qs from "qs";
const get = (url,data)=>{
let str = "";
for(var key in data){
str += "&"+key+"="+data[key];
}
url = url+str.substr(1);
return fetchPro(url,{
method:"GET",
headers:{
"content-type":"application/json"
},
credentials:"include"
})
.then(res=>res.json())
}
const post = (url,data)=>{
return fetchPro(url,{
method:"POST",
headers:{
"content-type":"application/x-www-form-urlencoded"
},
credentials:"include",
body:qs.stringify(data)
})
.then(res=>res.json())
}
export default {
get,
post
}

浙公网安备 33010602011771号