超好用超短的小程序请求封装

超好用超短的小程序请求封装,也不算特别特别短吧哈哈哈。但真的很好用的一个小程序请求封装,在请求的时候简短提高效率不需要将一样的东西重复写。下面就让大家看看这个封装是有多短,不够短的话也请别打我

网上多数使用的小程序封装是在单独的一个js文件,再使用module.exports进行输出方法。我所介绍的封装方法有异曲同工之妙,只不过是写在app.js里边,省去了使用时必须引用文件的麻烦。

app.js

xcxPost(options = {}) {
    wx.showLoading({ mask: true, title: '', })
    wx.request({
      url: this.globalData.postUrl + options._url,
      data: options._data || {},
      method: "POST",
      dataType: "json",
      header: this.globalData.header,
      success: (res) => {
        if (res.data.errcode > 0) {
          if (typeof options._success == "function") {
            options._success(res.data);
          }
        } else {
          this.xcxErrorToast({ title: res.data.errmsg || '服务器返回错误!' });
          return;
        }
      },
      fail: (res) => {
        if (typeof options._fail == "function") {
          options._fail(res);
        }
        if (typeof options._fail == "string") { //请求失败的弹框提示
          wx.showToast({ title: options._fail, icon: 'loading', duration: 2000 });
        }
      },
      complete: (res) => {
        if (typeof options._complete == "function") {
          options._complete(res);
        }
        wx.hideLoading()
      }
    });
  },

此处的this.globalData,是在app.js设置的,也就是小程序的全局属性,不了解的朋友请查阅小程序官方文档

而以上封装具体的返回参数说明,请移步官方文档   https://developers.weixin.qq.com/miniprogram/dev/api/network-request.html#wxrequestobject

App({
  globalData:{
    userInfo:{},
    postUrl: (wx.getExtConfigSync().request_url || '(后台接口地址)'),
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Cookie': ''
    },
  }, 

 

其他页面引用封装请求,比如 index.js

/**
   * http请求
   * 获得banner图
   */
  getShopId(callBack) {
    app.xcxPost({
      _url:'pc_home_page/banner',// 你需要发起的请求;
      _data: { type: '1' },// 你需要传的请求参数;
      _success: (resp) => {//请求成功后的操作;if (resp.errcode > -1) {
          // this.globalData.shopId = resp.list.shopId;
          // this.globalData.domainUrl = resp.list.domain;
          if (callBack) {
            callBack()
          }
        }
      }
    }) },

 

posted @ 2018-07-23 10:39  百撕可乐  阅读(2535)  评论(3编辑  收藏  举报
版权声明:本博客原创文章使用CC3.0授权协议,署名-非商业性使用-禁止演绎。转载本博客文章须在开头位置著名原作者姓名以及原文链接,违反协议的转载将受到我本人的版权追责。