超好用超短的小程序請求封裝


超好用超短的小程序請求封裝,也不算特別特別短吧哈哈哈。但真的很好用的一個小程序請求封裝,在請求的時候簡短提高效率不需要將一樣的東西重復寫。下面就讓大家看看這個封裝是有多短,不夠短的話也請別打我

網上多數使用的小程序封裝是在單獨的一個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()
          }
        }
      }
    }) },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM