封裝小程序請求API,實現請求和響應攔截(支持promise)

之前在寫公司小程序時由於大部分接口都需要傳入token參數,爲了方便,將請求API進行封裝,實現每次發送請求會同時自己添加token參數。這裏做個記錄避免以後忘了怎麼寫←_←

根目錄創建utils目錄,該目錄下面添加一個js文件,文件名隨意

var app = getApp()

//相同前綴的url
const baseUrl = app.globalData.url

function fun(url, method, data, header) {
  data = data || {}
  header = header || {}
  method = method

  let promise = new Promise(function(resolve, reject) {
    wx.request({
      url: baseUrl + url,
      header: header,
      //每個請求都提前自動傳遞token
      data: Object.assign({
        _token: app.globalData.token
      }, data),
      method: method,
      success: function(res) {
      //響應攔截
        console.log(res)
        //通過返回的code參數的不同進行後續不同的操作
        if (res.data.code) {
        //我們後臺規定當code爲110時,就代表當前沒有登錄
          if (res.data.code === 110) {
            util.showMessage('登錄失效,請重新登錄')
            setTimeout(() => {
            //跳轉到登錄頁面
              wx.reLaunch({
                url: '../login/login'
              })
            }, 1000)
            reject(res)
          } else if (res.data.responseCode) {
            let responseCode = res.data.responseCode

            //處理未綁定微信的情況
            if (responseCode === 103) {
                  wx.hideToast();
                  wx.showModal({
                    content: `${app.globalData.responseCode[responseCode]},即將轉到微信綁定頁面`,
                    showCancel: false,
                    confirmText: "確定",
                    success() {
                      //轉到綁定微信頁面
                        wx.reLaunch({
                          url: '../bind/bind'
                        })
                    }
                  })
     
              reject(res)
            } else {
              //其他情況,把響應編碼對應的提示信息已彈出框形式告知用戶
              wx.hideToast();
                  wx.showModal({
                    content: `${app.globalData.responseCode[responseCode]}`,
                    showCancel: false,
                    confirmText: "確定"
                  })
            }
          }
        }
        resolve(res)
      },
      fail: function(err) {
        reject(err)
      },
      complete: function() {
        //不管是success還是fail都會走這裏的函數
        wx.hideToast()
      }
    })
  })
  return promise
}

//導出模塊
module.exports = {
  baseUrl: baseUrl,
  "get": function(url, data, header) {
    return fun(url, "get", data, {
      'content-type': 'application/x-www-form-urlencoded'
    });
  },
  "post": function(url, data, header) {
    return fun(url, "post", data, {
      'content-type': 'application/x-www-form-urlencoded'
    })
  },
  "put": function(url, data, header) {
    return fun(url, "put", data, header);
  },
  "delete": function(url, data, header) {
    return fun(url, "delete", data, header);
  }
}

使用時

//引入
const request = require('../../utils/http')

//使用get方法
request.get("admin/sigin/getDistance", {
   lat: '111',
   lng: '111'
})
    .tnen(){}
    .catch(){}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章