微信小程序request 請求封裝

爲了避免在小程序開發中使用大量重複且臃腫的代碼,一般來說,開發者都會封裝一個請求以便於直接調用,這裏封裝了一個簡單簡單的請求:

let maxLen = 6, // 批量刪除圖片的最大值
responseArr = [];   // 存批量刪除圖片的響應數據

// 請求類封裝
class _nb {
  constructor () {
    this.baseURL = "https://ln.talkingcake.com/app";
    this.uploadURL = "https://ln.talkingcake.com/admin";
  }


  /* 
   * ajax 請求封裝  author displayli  2019.05.27
   * @path 路徑 
   * @data requestBody
   * @header null
   * @method 請求方法 「默認爲post」
   * @dataType json
   * @success 成功回調函數
   * @fail 失敗回調函數
   */ 

  wxrequest({ path, data, header, method, dataType, success, fail }){
        return new Promise((resolve, reject) => {
            wx.request({
                url: this.baseURL + path,
                data: data || {},
                header: header || {
                    "content-type": "application/json",
                    token: wx.getStorageSync("token") // 可有可無
                },
                method: method || "POST",
                dataType: dataType || "json",
                success: ({ data }) => {
                    // 如果code == 0 說明成功
                    if (!data.code) {
                        if (typeof success == 'function'){
                            success(data);
                        } else {
                            resolve(data);   
                        }
                    } else {
                        // 否則有問題出現
                        wx.showToast({
                            title: data.msg,
                            icon: "none",
                            duration: 500
                        });
                    }
                },
                fail: err => {
                    if (typeof fail == 'function'){
                        fail(err);
                    } else {
                        reject(err);   
                    }
                    console.error(new Error(err));
                }
            });
        });
    };



  /*
   * uplaod Image
   */ 
  
  uploadImg({ count, path, sizeType, sourceType, success, title, icon}) {
    return wx.chooseImage({
      count: count || 1,
      sizeType: sizeType || ['original', 'compressed'], // 可選擇原圖或壓縮後的圖片
      sourceType: sourceType || ['album', 'camera'],    // 可選擇性開放訪問相冊、相機
      success: res => {
        setTimeout(() => {
          wx.showToast({
            title: title || "上傳中...",
            icon: icon || 'loading',
            duration: 500
          })
        },800)
        // 調用上傳文件接口
        this.uploadFiles({ path, files: res.tempFilePaths }).then(res => {
          success(res); // 回調函數callback
        })
      }
    })
  }

  // 上傳文件方法
  uploadFiles({path,files}){
    let _this = this;
    return new Promise((resolve, reject) => {
      // 多文件上傳需要遍歷調接口 單個文件上傳不需要遍歷 直接循環去掉就好
      files.forEach((item, index) => {
        wx.uploadFile({
          url: _this.uploadURL + path,
          filePath: item,
          header: {
            'token': wx.getStorageSync('token')  // 可有可無
          },    
          name: 'img',   // 上傳文件規定的字段名
          success(res) {
          
            // 多文件上傳獲取響應值
            responseArr.push(res.data.URL);

            if (index == (files.length - 1)) {
              resolve(responseArr)
            }
            
            // 單個文件
            resolve(res.data)
          },
          fail(err) {
            reject(err);
            console.error(err);
          }
        })
      })
    })
  }
}

// 對外公開
module.exports = {
  _nb: new _nb()
};

當然你也可以直接將上面的三個方法直接寫在app.js中,然後全局調用即可,這個僅僅是把它們以模塊化的方式放在一個文件中而已
以上,請大家參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章