拒絕多bb,直接上代碼,以下是Fetch網(wǎng)絡(luò)封裝類宫患,遵循ES6規(guī)范。
class FetchUtil {
init(){
this.url = '';
this.method = 'GET';
this.headers = {};
this.body_type = 'form';
this.bodys = {};
this.credentials = 'omit';
this.return_type = 'json';
this.overtime = 0;
this.firstThen = undefined;
return this;
}
setUrl(url){
this.url = url;
return this;
}
setMethod(val){
this.method = val;
return this;
}
setBodyType(val){
this.body_type = val;
return this;
}
setReturnType(val){
this.return_type = val;
return this;
}
setOvertime(val){
this.overtime = val;
return this;
}
setHeader(name, val=null){
if(typeof name == 'string'){
this.headers[name] = val;
}else if(typeof name == 'object'){
Object.keys(name).map((index)=>{
this.headers[index] = name[index];
});
}
return this;
}
setBody(name, val=null){
if(typeof name == 'string'){
this.bodys[name] = val;
}else if(typeof name == 'object'){
Object.keys(name).map((index)=>{
this.bodys[index] = name[index];
});
}
return this;
}
setCookieOrigin(){
this.credentials = 'same-origin';
return this;
}
setCookieCors(){
this.credentials = 'include';
return this;
}
thenStart(then) {
this.firstThen = then;
return this;
}
dofetch(){
let options = {};
options.method = this.method;
options.credentials = this.credentials;
options.headers = this.headers;
if({} != this.bodys && this.method != 'GET'){
if('form' == this.body_type){
this.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
let data = '';
Object.keys(this.bodys).map((index) => {
let param = encodeURI(this.bodys[index]);
data += `${index}=${param}&`;
});
options.body = data;
}else if('file' == this.body_type){
let data = new FormData();
Object.keys(this.bodys).map((index) => {
data.append(index, this.bodys[index]);
});
options.body = data;
}else if('json' == this.body_type){
options.body = JSON.stringify(this.bodys);
}
}
return Promise.race([
fetch(this.url,options),
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('request timeout')), this.overtime ? this.overtime : 30 * 1000);
})
]).then(
(response) => {
if (this.firstThen) {
let tempResponse = this.firstThen(response);
if (tempResponse) {
return tempResponse;
}
}
return response;
}
).then(
(response) => {
if('json' == this.return_type){
return response.json();
}else if('text' == this.return_type){
return response.text();
}else if('blob' == this.return_type){
return response.blob();
}else if('formData' == this.return_type){
return response.formData();
}else if('arrayBuffer' == this.return_type){
return response.arrayBuffer();
}
}
);
}
}
module.exports = FetchUtil;
用法舉例:
POST請(qǐng)求
//工具類實(shí)例可重用手幢,建議一個(gè)實(shí)例化一次之后復(fù)用
let fetchUtil = new FetchUtil();
fetchUtil.init()
.setUrl('http://gank.io/api/random/data/Android/20')
.setMethod('POST')
.setOvertime(30 * 1000)
.setHeader({
'Accept': 'application/json',
'Content-Type': 'application/json',
'DEVICE-ID': 'iphone6',
'SYSTEM': 'ios/android',
})
.setBody('name', 'test')
.dofetch()
.then((data) => {
console.log('=> data: ', data);
})
.catch((error) => {
console.log('=> catch: ', error);
});
GET請(qǐng)求:
//工具類實(shí)例可重用捷凄,建議一個(gè)實(shí)例化一次之后復(fù)用
let fetchUtil = new FetchUtil();
fetchUtil.init()
.setUrl('http://gank.io/api/random/data/Android/requestData(params)?name=zhangsan&password=123456')
.setMethod('POST')
.setOvertime(30 * 1000)
.setHeader({
'Accept': 'application/json',
'Content-Type': 'application/json',
'DEVICE-ID': 'iphone6',
'SYSTEM': 'ios/android',
})
.dofetch()
.then((data) => {
console.log('=> data: ', data);
})
.catch((error) => {
console.log('=> catch: ', error);
});
以下是方法說(shuō)明:
init() 初始化工具類
setUrl(url:string) 設(shè)置請(qǐng)求URL
setMethod(method:string) 設(shè)置請(qǐng)求方式,
'GET'/'POST'/'PUT'/'DELETE'
围来,默認(rèn)'GET'
setBodyType(type:string) 設(shè)置請(qǐng)求body類型跺涤,
'form'/'file'/'json'
,默認(rèn)'form'
setReturnType(type:string) 設(shè)置返回data類型管钳,
'json'/'text'/'blob'/'formData'/'arrayBuffer'
钦铁,默認(rèn)'json'
setOvertime(time:number) 設(shè)置超時(shí)時(shí)間,毫秒
setHeader(name:string/object, value:string) 設(shè)置Header才漆,name若為字符串牛曹,則name和value為header鍵值對(duì)數(shù)據(jù),若name為object醇滥,則name為header鍵值對(duì)對(duì)象
setBody(name:string/object, value:string) 設(shè)置請(qǐng)求body黎比,參數(shù)同上
thenStart(then:function) 設(shè)置請(qǐng)求成功后第一個(gè)回調(diào)方法then,通常用于處理網(wǎng)絡(luò)返回的第一筆數(shù)據(jù)鸳玩,需要將此對(duì)象return出去阅虫,交由后面的then處理
dofetch() 執(zhí)行請(qǐng)求