小程序HTTP請求封裝

1、封裝思想是什麼?

提取公共部分,預留修改部分。提供修改參數接口。json

2、小程序HTTP 封裝

const app = getApp()
let rootDocment = ''
let streamId = null
let deadline = null

function setStreamId (id, time) {
  streamId = id
  deadline = time
}
function getStreamId () {
  if (deadline && deadline > new Date().getTime()) {
    return streamId
  } else {
    app.globalData.token = null
    app.globalData.user.userInfo = {}
    return null
  }
}

function send (options) {
  let { url, header, method, data, success } = options
  let finalHeader = {
    'Accept': 'application/json',
    ...(header || {})
  }
  finalHeader['X-Stream-Id'] = getStreamId()
  wx.showLoading({
    mask: true,
    title: '數據正在加載中'
  })
  wx.request({
    url: rootDocment+url,
    header: finalHeader,
    method: method,
    data: data,
    success: function (res) {
      if (res.data.success) {
        success(res)
      } else {
        wx.showToast({
          title: '網絡請求錯誤' + res.data.error_code,
          icon: 'none',
          duration: 2500
        })
      }
    },
    fail: function () {
      wx.showToast({
        title: '網絡請求錯誤',
        icon: 'none',
        duration: 2500
      })
    },
    complete: function () {
      wx.hideLoading()
    }
  })
}

module.exports = {
  send,
  setStreamId
}

複製代碼
相關文章
相關標籤/搜索