封装 wx.request 实现Promise、beforeRequest、afterRequest

封装代码

class Request {
  constructor(options = {}) {
    // 请求的根路径
    this.baseUrl = options.baseUrl || ''
    // 请求的 url 地址
    this.url = options.url || ''
    // 请求方式
    this.method = 'GET'
    // 请求的参数对象
    this.data = null
    // header 请求头
    this.header = options.header || {}
    this.beforeRequest = null
    this.afterRequest = null
  }

  get(url, data = {}) {
    this.method = 'GET'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  post(url, data = {}) {
    this.method = 'POST'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  put(url, data = {}) {
    this.method = 'PUT'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  delete(url, data = {}) {
    this.method = 'DELETE'
    this.url = this.baseUrl + url
    this.data = data
    return this._()
  }

  _() {
    // 清空 header 对象
    this.header = {}
    // 请求之前做一些事
    this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
    // 发起请求
    return new Promise((resolve, reject) => {
      let weixin = wx
      // 适配 uniapp
      if ('undefined' !== typeof uni) {
        weixin = uni
      }
      weixin.request({
        url: this.url,
        method: this.method,
        data: this.data,
        header: this.header,
        success: (res) => { resolve(res) },
        fail: (err) => { reject(err) },
        complete: (res) => {
          // 请求完成以后做一些事情
          this.afterRequest && typeof this.afterRequest === 'function' && this.afterRequest(res)
        }
      })
    })
  }
}

export const $http = new Request()

注意:这是使用 class关键词 声明的一个类,里面的this默认指向的是实例对象。因为class声明的类,默认是开启严格模式的。

使用 beforeRequest、afterRequest   拦截请求、拦截响应

// 导入请求的包
import { $http } from './http.js'

// 绑定到 uni全局对象上
uni.$http = $http

// 设置基地址
$http.baseUrl = 'https://wwww.xxxxx.com'

// 定义拦截请求器的方法
$http.beforeRequest = function(options) {
    // 这里的options 是当前$http 实例对象的 this指向
    console.log(options)
    
    // 判断请求是否为有权限的 API 接口
    if(options.url.indexOf('/my/') !== -1) {
        // 为请求头添加身份认证字段
        options.header = { 
            Authorization: store.state.m_user.token
        }
    }
}


// 定义拦截响应器的方法
$http.afterRequest = function(options) {
    // 这里的 options 是响应回来的 res
    console.log(options)
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值