小程序 wx.request封装

 

/util/http/request.js 封装

/**
 * 网络请求的公共方法
 *    1.基本方法
 *    2.为了后续获取数据方便。promise处理:fetch axios基于promise
 *    3.对获取数据的状态处理: loadding toast
 *    4.对请求头的处理。机型、大小、系统、屏幕
 */

let system = wx.getSystemInfoSync()

const clientInfo = {
  'clientType': 'clientType',
  'appName': 'appName',
  'brand': system.brand, //设备品牌
  "model": system.model, //设备型号
  "os": system.system, //操作系统及版本
  "screen": system.screenWidth + '*' + system.screenHeight, //屏幕分辨率
  "version": App.version, //自定义小程序版本
  "chennel": "miniprogram"
}

const requestSync = (url, data, method, option) => {
  let {
    loadding = true, toast = true
  } = option;
  return new Promise((resolve, reject) => {
    if (loadding) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'clientInfo': JSON.stringify(clientInfo)
      },
      success(res) {
        if (loadding) {
          wx.hideLoading();
        }
        let statusCode = res.statusCode; //res.data {code:200, message:"", data:""}
        if (statusCode == 200) {
          resolve(res)
        } else {
          reject(res)
          if (toast) {
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
          }
        }
      },
      fail(err) {
        let msg = err.errMsg;
        if (msg == 'request:fail timeout') {
          msg = '请求超时,请稍后处理'
        }
        wx.showToast({
          title: msg,
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

const http = {
  get: function (url, data, option = {}) {
    return requestSync(url, data, 'GET', option)
  },
  post: function (url, data, option = {}) {
    return requestSync(url, data, 'POST', option)
  },
  put: function (url, data, option = {}) {
    return requestSync(url, data, 'PUT', option)
  },
  delete: function (url, data, option = {}) {
    return requestSync(url, data, 'DELETE', option)
  }
}

module.exports = {
  http
}

xxx.js 调用

const http = require("../../utils/http/request.js").http;

let data = {}
http.post("https://xxx.com", data)
  .then(res => {
    console.log('成功:', res)
  }).catch(err => {
    console.log('失败:', err)
  })

OK.


版权声明:本文为weixin_43789195原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。