微信小程序wx.request的封装

785 阅读1分钟

功能:

1、改成Promise

2、添加baseUrl

3、添加拦截器

const request = (function() {

  function Axios() {
    this.defaults = {
      baseUrl: ''
    };
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }

  Array.prototype.forEach.call(['get', 'delete', 'post', 'put', 'options', 'head', 'trace', 'connect'], function(method) {
    Axios.prototype[method] = function(url, data, config) {
      return this.wxRequest(merge(
        this.defaults, {
          url: url,
          method: method,
          data: data
        },
        config || {}))
    }
  });

  Axios.prototype.wxRequest = function(config) {
    return new Promise((resolve, reject) => {
      config = this.interceptors.request.func(config)
      config.url = config.url.startsWith('http') ? config.url : config.baseUrl + config.url
      config.success = (res) => {
        resolve(this.interceptors.response.func(res));
      };
      config.fail = (res) => {
        reject(this.interceptors.response.func(res));
      }
      wx.request(config);
    })
  }

  function InterceptorManager() {
    this.func = function(data) {
      return data
    }
  }

  InterceptorManager.prototype.use = function(fn) {
    this.func = fn;
  }

  function merge(axiosDefaultConfig, data, config) {
    let cloneAxios = deepClone(axiosDefaultConfig)
    let cloneData = deepClone(data)
    let cloneConfig = deepClone(config)
    return Object.assign(cloneAxios, cloneData, cloneConfig)
  }

  // 深拷贝
  function deepClone(obj) {
    let _obj = JSON.stringify(obj),
      objClone = JSON.parse(_obj);
    return objClone
  }

  return new Axios()
})()

/**
 * default 或者 config参数说明
 * 
    baseUrl: string                  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是http或https开头的。
    
  以下参数参照 wx.request
    url: string                      // `url` 是用于请求的服务器 URL
    header:Object                    
    method:string
    data: string/object/ArrayBuffer
    dataType:string
    responseType:string
 */


/**
 * baseUrl设置
 * 
 * request.defaults.baseUrl = 'https://www.zhangshuda.com/api/'
 */

/**
 * 请求拦截器设置
 * 
 * request.interceptors.request.use(function(config) {
 *    return config
 * })
 * 
 */

/**
 * 响应拦截器
 * 
 * request.interceptors.response.use(function(response) {
 *    return response
 * })
 * 
 */


/**   
 * get请求 
 * request.post(url[, data[, config]]);
 * 
 * 如:请求https://www.zhangshuda.com/api/const/getConstByKey?key=notice
 *    request.get('/const/getConstByKey', {key:notice}).then(res=>{}).catch(err=>{});
 **/


/** 
 * post请求
 * request.post(url[, data[, config]]);
 * 
 * 如:请求https://www.zhangshuda.com/api/notice/listPortalNotice
 *    request.post('/notice/listPortalNotice', {id: 11}).then(res=>{}).catch(err=>{});
 **/

/** 
 * 请求多个
 * Promise.all([request.get('/const/getConstByKey', {key:notice}), request.post('/notice/listPortalNotice', {id: 11})]).then(resArr=>{}).catch(err=>{})
 * 
 **/


module.exports = request;

有哪些不足之处请留言