ES7标准 fetch请求封装

原文地址:http://blog.csdn.net/BingHongChaZuoAn/article/details/52851980
作为一个程序猿,一定要养成一个爱学习的好习惯,因为程序员是一个终身学习的职业,要时刻把Live and learn作为一种信仰。I can’t change the world,only change myself。

闲话少说,言归正传,今天跟大家分享下我自己封装的延用ES7标准的 fetch请求,不好之处忘大家见谅。

首先是 Header model类型,配置文件 header.js。

let Header = {
  'Accept': 'application/json',
  //json形式
  'Content-Type': 'application/json'
}

module.exports = Header;

netTools.js

export default {
  /*检查对象是否为空*/
   isEmpty(obj){
      for (var r in obj){return false;}
      return true;
  },

  /*把String转化成对象*/
  toObj(obj){
    if(typeof obj === 'object'){
        return obj;
    }else{
        return eval('('+obj+')');
    }
  },

  /*判断对象是否为空*/
  isNull(obj){
    return (!obj && typeof(obj)!="undefined" && obj!=0)?true:false;
  },

}

NetUtil.js

'use strict';

import React, { Component} from 'react';

var Header = require('./header');

class NetUitl extends Component {

  constructor(props){
      super(props);
      this.state ={
        headers:Header,//选中的位置
      };

  }

  /**
  *url :请求地址
  *data:参数(Json对象)
  *callback:回调函数
  */
static async fetchAsync (hostUrl, methodUrl, method, data, callback) {

    let   fetchOptions;

    if(method === 'get'){
      fetchOptions = {
        method: 'GET',
        mode: "cors",
        headers: Header,
        credentials: 'include',
      };
    } else if(method === 'post'){
      fetchOptions = {
        method: 'POST',
        mode: "cors",
        headers: Header,
        credentials: 'include',
        body: JSON.stringify(data),
      };
    }

  //  alert(JSON.stringify(fetchOptions));
  let LOGIN_REQUEST= this.transform(hostUrl,methodUrl,data);
  LOGIN_REQUEST = encodeURI(LOGIN_REQUEST);
//由于我们的服务器有点问题,只支持url拼接参数的方式传值,所以只能这么写了
  try {
     let response = await fetch(LOGIN_REQUEST, fetchOptions);
     let responseJson = await response.json();
    //  alert(JSON.stringify(responseJson));
     callback(responseJson);
   } catch(error) {
     console.error(error);
   }

  }

  static addHeaders(obj)
  {
      for(var r in obj){
      eval("Header."+r+"=obj."+r);
      }
      return Header;
  }

  static clearHeader(){
    Header={};
    return Header;
  }

  static changeHeader(key,value)
  {
      for(var r in Header){
        if(r==key){
          eval("Header."+key+"="+JSON.stringify(value));
          return Header;
        }
      }
      console.log('not find header:'+key);
  }

  static deleteHeader(key)
  {
    eval("Header."+key+"=undefined");
    return Header;
  }

/**
* 对象解析变换,目前只支持简单对象变换。
*/
  static transform(hostUrl, methodUrl, obj){

    let responseUrl = hostUrl+ methodUrl+'?';
    for(var key in obj){//用javascript的for/in循环遍历对象的属性
      responseUrl += key+"="+obj[key]+"&";
    }
    // alert(responseUrl);
    let index = responseUrl.lastIndexOf('&');
    responseUrl = responseUrl.substring(0,index);
    return responseUrl;

  }


}

module.exports = NetUitl;```



http.js

let NetUitl = require('./NetUtil');
import Tools from './netTools';

function fetchAction(...props) {
  this.hostUrl = props.shift(1);
  this.methodUrl = props.shift(1);
  this.method = props.shift(1);
  this.header = props.shift(1);
  this.params = props.shift(1);
  this.callback = props.shift(1);
  // this.failureDo = props.shift(1);
  // this.finallyDo = props.shift(1);

  // alert(!Tools.isEmpty(this.header));

  if(!Tools.isEmpty(this.header)){
    NetUitl.addHeaders(this.header);
  }

  NetUitl.fetchAsync(this.hostUrl, this.methodUrl,this.method, this.params,
    (code, msg, data)=>{this.callback(code, msg, data);},
    );
}
export default {

  post(hostUrl,methodUrl, params,callback){
    fetchAction(hostUrl,methodUrl, 'post',null, params,callback);
  },

  postWithHeader(hostUrl,methodUrl, headers, params,callback){
      fetchAction(hostUrl,methodUrl, 'post', headers, params,callback);
  },

  get(hostUrl,methodUrl, params,callback){
    fetchAction(hostUrl,methodUrl, 'get', null, params,callback);
  },

  getWithHeader(hostUrl,methodUrl, headers, params,callback){
      fetchAction(hostUrl,methodUrl,'get', headers, params,callback);
  },

}

API.js


onst HOSTURL= 'http://xxxx';

import Http from './http';

export default {

  getDetail(params,callback) {
    let methodUrl = 'xxxx';
    let header = {xxx:xxx};
     Http.post(HOSTURL,methodUrl, params,callback);
     //Http.post(HOSTURL,methodUrl, header ,params,callback);
      //Http.get(HOSTURL,methodUrl, params,callback);
     //Http.get(HOSTURL,methodUrl, header ,params,callback);
  },
}

上述已经封装完成。接下来,看看如何调用吧。


let params={'kw':'w'};
     Api.getDetail(params,(response)=>{
             alert(JSON.stringify(response));
         },
     );

“`

以上基本完成了fetch请求的封装,包括动态添加、删除、修改header。允许携带cookie。之所以没有让fetch可以动态设置cookie,是因为fetch请求本身不太完善,需要做一些设置,git上有一套方案,不过好像用了他的,header就不能动态设置了,最近比较忙,也没时间深入研究,暂时就这样吧,以后深入研究下人家的东西,再慢慢优化。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值