axios封装

axios.js


```handlebars

```handlebars
import axios from 'axios' // 引入axios
import Vue from 'vue'
import { errorStatus } from '@/utils/api/err'
import { getToken } from '@/utils/auth'
import { Loading } from 'element-ui'
import _ from 'lodash'
let loadingInstance // loading 实例
let needLoadingRequestCount = 0 // 当前正在请求的数量

function showLoading() {
  const main = document.querySelector('#app')
  if (main) {
    if (needLoadingRequestCount === 0 && !loadingInstance) {
      loadingInstance = Loading.service({
        fullscreen: true,
        target: main,
        text: '',
        customClass: 'loadingClass',
        background: 'rgba(207,204,204,0.1)'
      })
    }
    needLoadingRequestCount++
  }
}

function closeLoading() {
  Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
    needLoadingRequestCount--
    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 保证大于等于0
    if (needLoadingRequestCount === 0) {
      if (loadingInstance) {
        hideLoading()
      }
    }
  })
}
// 防抖:将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时, loading闪烁的问题。
// 因为有时会碰到在一次请求完毕后又立刻又发起一个新的请求的情况(比如删除一个表格一行后立刻进行刷新)
// 这种情况会造成连续 loading 两次,并且中间有一次极短的闪烁。通过防抖可以让 300ms 间隔内的 loading 便合并为一次,避免闪烁的情况。
var hideLoading = _.debounce(() => {
  loadingInstance.close()
  loadingInstance = null
}, 300)

class HttpRequest {
  constructor(url) {
    this.baseUrl = url
    this.loading = {
      close: () => {
        console.log('关闭')
      }
    }
  }

  // 获取传入的相关配置
  getConfig(options) {
    const { headers, config } = options
    return {
      // 设置header
      headers: {
        'Content-Type': headers[ 'Content-Type'] ? headers[ 'Content-Type'] : 'application/json',
        'authorization': `Bearer ${getToken() ? getToken() : ''}`,
        ...headers
      },
      // 设置超时间
      timeout: 50000,
      // 是否携带cookies
      withCredentials: false,
      // 设置请求地址
      baseURL: this.baseUrl ? this.baseUrl : '',
      ...config
    }
  }

  // 请求拦截
  interceptors(Ajax) {
    // 请求拦截
    Ajax.interceptors.request.use(config => {
      return config
    }, err => {
      closeLoading()  // 请求失败关闭loading
      return Promise.reject(err)
    })

    // 响应拦截
    Ajax.interceptors.response.use(res => {
      closeLoading()
      return Promise.resolve(errorStatus(res))
    }, err => {
      closeLoading()
      return Promise.reject(err)
    })
  }

  // 请求
  request(options) {
    const Ajax = axios.create()
    // 加载状态
    if (options.headers.loading) {
      showLoading()
    }
    options = Object.assign({}, options, this.getConfig(options))
    // 拦截器
    this.interceptors(Ajax)
    return Ajax(options)
  }
}

export default new HttpRequest()  // baseUrl 需要的可以暴露HttpRequest 传递

http.js

// 二次封装axios请求方式
import axios from '@/utils/api/axios'

class Http {
  get(url = '', params = {}, options = {}, config = {}) {
    return axios.request({
      url: url,
      method: 'get',
      params: params,
      headers: options,
      config
    })
  }
  post(url = '', params = {}, options = {}, config = {}) {
    return axios.request({
      url: url,
      method: 'post',
      data: params,
      headers: options,
      config
    })
  }
  put(url = '', params = {}, options = {}, config = {}) {
    return axios.request({
      url: url,
      method: 'put',
      data: params,
      headers: options,
      config
    })
  }
  delete(url = '', params = {}, options = {}, config = {}) {
    return axios.request({
      url: url,
      method: 'delete',
      data: params,
      headers: options,
      config
    })
  }
}

export default new Http()

使用示例

import http from '@/utils/api/http'

export const rtcList = (data, cb) => http.post(url, data, { loading: true },{onUploadProgress:cb})
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值