小程序封装request

request.js

const debug = false

const basePath='192.168.1.100/'  //调试接口地址

const API = {
    user:(userId) => basePath + "index/user/" + userId, //用户信息
}

// 加载动画
function loadingAnimate() {
  wx.showLoading({
    title: "加载中",
    mask: true
  });
}
// 请求接口
function request(options = {}) {
  // 根据showLoading参数决定是否显示加载效果
  let showLoading = options.showLoading ? options.showLoading : false
  if (showLoading) loadingAnimate()
  // 默认头部
  if (options.header === undefined) {
    options.header = {
      'content-type': 'application/json'
    }
  }
  // 如果token有值则带上
  let token = wx.getStorageSync("desKey");
  if (token) {
    options.header = Object.assign({}, options.header, {
      'Authorization': token
    });
  }
  options.method = options.method ? options.method : 'GET'
  return new Promise((resolve, reject) => {
    options.success = res => {
      debug && sendErrLog(options, 'success')
      if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
        //服务端业务处理正常结束
        resolve(res)
      } else {
        reqStatus(res.data.errCode)
        reject(res)
      }
    }
    options.fail = err => {
      sendErrLog(err, 'fail')
      reject(err)
    }
    options.complete = res => {
      wx.hideLoading()
    }
    wx.request(options)
  })
}
// 日志输出
function sendErrLog(req, status) {
  let title = '调用微信请求接口成功!'
  if (status == 'fail') {
    title = '请求接口错误!'
  }
  console.group(title)
  console.info("[请求Url]", req.url)
  console.info("[请求Header]", req.header)
  console.info("[请求Data]", req.data)
  if (status == 'fail') console.info("[请求Result]", req)
  console.groupEnd();
}
// 接口状态判断
function reqStatus(statusCode) {
  switch (statusCode) {
    case 401:
      wx.showModal({
        content: "您的账号已在别处登录,请刷新页面重新登录",
        showCancel: false,
        success: data => {
          wx.redirectTo({
            url: "../login/login"
          })
        }
      });
      break;
    case 503:
      wx.showModal({
        content: "服务繁忙,请稍后再试!",
        showCancel: false
      });
      break;
    default:
      break;
  }
}
module.exports={
    API,
    request
}

// 使用
index.js

const req = require('../util/request')
const userId = wx.getStorageSync("userId")
req.request({
    url: req.API.user(userId)
}).then(res=>{
    //code
})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值