微信小程序的請求封裝

微信小程序的請求是基於微信API來實現、因此寫了一個獨立的 http.js來實現主要的請求如 POST、GET操做,代碼以下:小程序

/**
 * 請求相關的封裝
 */
let baseUrl = "http://xxxxxx.com/api/"; // 接口地址
let header = {
  'content-type': 'application/x-www-form-urlencoded',
  'Authorization': "Bearer " + wx.getStorageSync("token")
}
/**
 * 封裝請求
 */
function fetch(options) {
  if (options.loading) {
    wx.showLoading({
      title: '加載中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + options.url,
      data: options.data,
      header: header,
      method: options.method,
      success: function(res) {
        if (options.loading) {
          wx.hideLoading()
        }
       
        if (res.data.Code == 1) {
          // 從新登錄
          return false;
        }
        if (res.data.Code != 0) {
          wx.showToast({
            title: res.errMsg,
            mask: "true",
            icon: 'none',
            duration: 3000
          })
          return;
        }
        resolve(res.data); //把請求到的數據發到引用請求的地方
      },
      fail: function(err) {
        if (options.loading) {
          wx.hideLoading()
        }
        wx.showToast({
          title: "網絡鏈接超時",
          icon: 'none',
          duration: 3000,
        })
      }
    })
  })
}
/**
 * POST 請求
 */
export function post(url, params, loading = true) {
  console.log(params, loading);
  var option = {
    url: url,
    data: params,
    method: 'POST',
    loading
  }
  return fetch(option);
}

/**
 * GET請求
 */
export function get(urls, params, loading = true) {
  console.log(params, loading);
  var option = {
    url: urls,
    data: params,
    method: 'GET',
    loading
  }
  return fetch(option);
}

在業務上調用,先經過模塊化引入
let http = require('../../common/http.js')
小程序官方也推薦使用require非import微信小程序

使用的時候能夠用async await
也能夠使用以下方式
Get請求api

http.get('getuserInfo', params).then(function (res) {
      console.log(res)
    })

Post請求微信

http.post('getuserInfo', params).then(function (res) {
      console.log(res)
    })

固然其餘須要的能夠繼續擴展,一般業務上的攔截都只能以CODE來作常規操做,如跳轉,提示等。網絡

相關文章
相關標籤/搜索