微信小程序-wx.request的封装实现

httpExt.js

const app = getApp()
const util = require('/util.js')

/**
 * wx.request的封装
 * 使用方式: httpExt.get("admin/login", {}).then(res => {}).catch(err => {})
 * @param {*} url 请求地址
 * @param {*} method 请求类型
 * @param {*} data 请求参数
 * @param {*} options 接口配置
 */
const request = (url, method, data, options) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: util.getUrl(url),
      method: method || 'GET',
      data: method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        // 'token': wx.getStorageSync("SSP_token")
      },
      success(res) {
        if (res.data.success == true) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail(error) {
        reject(error)
      },
      complete: info => {
        wx.hideLoading()
      }
    })
  })
}

const get = (url, data = {}, options = {}) => {
  return request(url, 'GET', data, options)
}
const post = (url, data = {}, options = {}) => {
  return request(url, 'POST', data, options)
}
module.exports = {
  get,
  post
}

util.js

const hosts = require("/hosts.js")

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}


const getUrl = (url) => {
  if (url.indexOf('://') == -1) {
    url = hosts.actualHost.mainHostName + url;
  }
  return url
}

module.exports = {
  getUrl,
  formatTime
}

hosts.js

// pro 生产环境 sit 测试环境 (上线前需要修改为'pro')
const hostType = 'sit'
const version = '1.0'

const host = {
  /**
   * 主服务域名
   */
  mainHostName: new Map([
    ['pro', 'xxxxx'],
    ['sit', 'xxxxxx']
  ])
}

const actualHost = {
  mainHostName: host.mainHostName.get(hostType)
}

export {
  actualHost,
  hostType,
  version
}

使用:

const httpExt = require('../../utils/httpExt.js')

          httpExt.get("xxxx", {}).then(res => {
            // 接口成功操作
          }).catch(err => {
            console.log("error:", err);/*  */
            // 接口失败操作
            wx.showToast({
              title: err.data.msg||"服务异常,请稍后重试!",
              icon: 'error',
              duration: 2000
            })
          });
原文地址:https://www.cnblogs.com/zhaomeizi/p/14442066.html