小程序 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值