关于wx.request的封装

最近打算自己做个小程序,也在不断学习微信小程序官方文档。然而在小程序中网络请求是也是非常重要的一部分,但是一个应用中会有许多的请求,所以需要对一个请求做一些拦截,于是就像对wx.request方法做一个分装方便使用。

封装之前先看下微信小程序官方的 wx.request 方法使用。
其实官方的请求方法很简单, 就是 wx.request(options) 其中options包含了很多的指定参数。

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

基于我在想如何封装一个方便自己使用的请求方法呢,主要的考虑点如下:

  1. 请求可以统一拦截处理;
  2. 能添加统一公共的请求体参数,例如一些加密处理等;
  3. 请求头部添加公共参数;
  4. 请求统一处理部分。

具体实现步骤

  1. 为了习惯使用封装一个Fetch类
  2. 添加请求Header、状态码处理、请求结果处理。
class Fetch {
    constructor({
        processAuthorizationHeader = () => {},
        processHttpStatusCode = defaultHttpStatusCode,
        processResultHandle = noop
    }) {
        this.processAuthorizationHeader = processAuthorizationHeader;
        this.processHttpStatusCode = processHttpStatusCode;
        this.processResultHandle = processResultHandle;
    }

    fetch(opts) {
        let {
            url,
            data = {},
            header = {},
            method = 'POST', // 有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            dataType = 'json',
            responseType = 'text',
            complete = noop,
            noStatus = true, // 默认不显示loading
            mask = false, // 不显示遮罩
            loadingText,
        } = opts;
        const self = this;
        // loading icon
        if (!noStatus) {
            wx.showLoading({
                title: loadingText || '加载中…',
                mask: mask
            })
        }

        // 请求头设置
        header = Object.assign({}, this.getUserAuthorizationHeader(), header);

        return new Promise((resolve, reject) => {
            wx.request({
                url,
                data,
                header,
                method,
                dataType,
                responseType,
                complete,
                success: (res) => {
                    wx.hideLoading();
                    // 请求状态码处理
                    const httpStatusCode = res.statusCode;
                    if (!self.processHttpStatusCode(httpStatusCode)) {
                        return reject();
                    }

                    // 请求数据过滤(data默认为json格式)
                    if (typeof res.data === 'string') {
                        try {
                            res.data = JSON.parse(res.data);
                        } catch (e) {}
                    }

                    // 统一添加请求处理
          self.processResultHandle(res) && resolve(res.data);
                },
                fail: (res) => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '网络异常',
                        duration: 1200
                    });
                    reject(res);
                }
            });
        })
    }
}

// 请求默认处理方法
function defaultHttpStatusCode(statusCode) {
    if (statusCode === 200) {
        return true;
  }
  wx.showToast({
    title: '请求异常',
    icon: 'none',
  })
    return;
}

// 空方法
function noop() {
    return true;
}

export default Fetch;

使用方式

  1. 实例化一个Fetch类
  2. 将实例化的对象挂到wx.fetch下面,这样就可以通过wx.fetch的方式处理做请求。
export const myFetch = new Fetch({
  processAuthorizationHeader() {
    return {
      'usercode': wx.getStorageSync('usercode'),
    }
  },
  processHttpStatusCode(statusCode) {
    if (statusCode === 200) {
      return true;
    } else {
      wx.showToast({
        title: '服务器错误',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
  },
  processResultHandle(res) {
    if (+res.data.code === 200) {
      return true;
    } else if (+res.data.code === 401) { // 重新登录
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return false;
    } else { // 错误异常
      wx.showToast({
        title: res.data.msg,
        icon: 'none',
        duration: 2000
      })
      return false;
    }
  }
})

wx.fetch = myFetch.fetch.bind(myFetch); // 将实例化的对象挂到wx.fetch下
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,771评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,823评论 25 709
  • 忙完了,放松了,忽而难过到想死,因为我想起了过往,又做贱了自己,忽而又被感动打湿了眼眶。我很伤心,我的过去有你,但...
    东夙阅读 1,118评论 0 0
  • 去年年底为舍友临摹的梅长苏,曾在她背包离去前提醒过她一次,可这幅画却终是因被忘记而继续留在了我的画册里。 大概冥冥...
    觅渡雅朵阅读 2,206评论 2 2
  • 晚安【日精进第75天/3650用生命影响生命!如何过一天就如何过一生! 没有反思的人生不值得过!!(湖北省恩施市)...
    好心情_d8eb阅读 825评论 0 0