微信小程序的请求封装

微信小程序的请求是基于微信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来作常规操做,如跳转,提示等。网络

相关文章
相关标签/搜索