1. 程式人生 > >Fetch網路請求簡單封裝

Fetch網路請求簡單封裝

//fetch網路請求簡單封裝,支援超時入口
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;
  }
  //設定請求URL
  setUrl(url){
      this.url = url;
      return this;
  }
  //設定請求方式,預設為GET請求(POST,PUT,DELETE)
  setMethod(val){
      this.method = val;
      return this;
  }
  //設定請求body型別,預設為for也可以是file/json,
  setBodyType(val){
      this.body_type = val;
      return this;
  }
  //設定返回data型別,預設為json,也可以是text,blob,formData/arryBuffer
  setReturnType(val){
      this.return_type = val;
      return this;
  }
  //設定超時時間,單位毫秒
  setOvertime(val){
      this.overtime = val;
      return this;
  }
  //設定Header,name若為字串,則name和value為Header鍵值對資料;若name為object,則name為header鍵值對物件
  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;
  }
  //設定請求body,name若為字串,則name和value為Header鍵值對資料;若name為object,則name為header鍵值對物件
  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;
  }
  //設定請求成功後第一個毀調方法,通常用於網路返回的第一筆資料,需要將此物件return出去,交由後面的then處理
  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請求方式

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請求方式

//工具類例項可重用,建議一個例項化一次之後複用

 let fetchUtil = new FetchUtil();
 fetchUtil.init()
    .setUrl('url')
    .setMethod('GET')
    .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);
    });