axios进行封装,可自定义loading及Error提示等功能

需求背景

对于post请求进行封装,在每个页面中都去写Loading及Error提示很麻烦,整体封装在一起去使用。在每次请求前去添加token等公共的参数

文件目录

在inject下新建了一个axios.js文件去封装request
在config下interceptors中新建了一个axios.js文件去处理公共参数

代码
  • 把loading及Error挂载到Vue的prototype上(请看下一篇文章)

  • 封装

import axios from 'axios'
import CON from '@conf'
import Vue from 'vue'

let axiosInstance = {}

axiosInstance = axios.create(CON.AXIOS_DEFAULT_CONFIG)
// axiosInstance.defaults.headers.Cookie = 'dev_gaia_session_id=b7666dfb-ceeb-4da6-91ef-6419322f964d'

// 注入请求拦截
axiosInstance
  .interceptors.request.use(
    CON.INTERCEPTORS.requestSuccess,
    CON.INTERCEPTORS.requestFail
  )

// 注入响应拦截
axiosInstance
  .interceptors.response.use(
    CON.INTERCEPTORS.responseSuccess,
    CON.INTERCEPTORS.responseFail
  )
function request ({ url, method = 'post', options = { loading: true, handleError: true }, data, ...rest }) {
  return new Promise((resolve, reject) => {
    if (options.loading) Vue.prototype.$showLoading('数据加载中...')
    axiosInstance({
      url,
      method,
      data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        options,
        ...rest
      }
    }).then(res => {
      if (res.code === 200) {
        resolve(res)
      } else {
        if (res.code === 301) {
          Vue.prototype.$toast('您当前无编辑权限,仅支持查看!')
          Vue.prototype.$storage.remove('token')
          Vue.prototype.$storage.remove('jurisdiction')
          setTimeout(() => {
            const backlen = history.length - 1
            Vue.prototype.$storage.set('isRedirect', true)
            history.go(-backlen)
            // location.href = utils.wxAuthUrl(location.origin + '/loginBase')
          }, 1500)
          return
        }
        if (options.handleError) {
          Vue.prototype.$toast(res.message)
        }
        resolve(res)
      }
    }).catch(err => {
      if (options.handleError) {
        if (err.message.includes('Network Error')) {
          Vue.prototype.$toast('网络中断,请稍后重试')
        } else {
          Vue.prototype.$toast(err.message)
        }
      }
      reject(err)
    }).finally(() => {
      Vue.prototype.$hideLoading()
    })
  })
}
export {
  request
}
export default axiosInstance
  • 请求响应拦截
export const requestSuccess = res => {
  res.baseURL = envConfig.getConfig('host', res.baseURL)
  let file = null
  console.log('request=res', res)
  if (_handleUrlStatus(res.url)) {
    // 处理文件上传接口
    file = new FormData()
    file.append('file1', res.data.file)
    delete res.data.file
  }
  global.$utils.filterParams(res.data || {})
  if (res.method === 'post') {
    res.headers.timestamp = new Date().getTime()
    res.headers['x-perm-id'] = envConfig.getConfig('x-perm-id') || 'broker_portal'
    res.headers['x-app-key'] = envConfig.getConfig('app-key') || 'broker_portal'
    res.headers['x-broker-token'] = envConfig.getConfig('x-broker-token') || storage.get('token')
    res.headers.latitude = JSON.parse(storage.get('location') || '{}').latitude || ''
    res.headers.longitude = JSON.parse(storage.get('location') || '{}').longitude || ''
    res.headers.sign = global.$utils.signGenerate(res.data)
    if (_handleUrlStatus(res.url)) {
    // 处理文件上传
      Object.keys(res.data).forEach(key => {
        file.append(key, res.data[key])
      })
      res.data = file
      return res
    }
    if (!res.headers['Content-Type'].includes('json')) {
      // 上传是json时,需要额外处理
      res.data = Qs.stringify(res.data)
    }
  }
  return res
}

/**
 * 拦截器发起请求失败
 *
 * @export
 * @param {*} requestError
 * @returns
 */
export const requestFail = requestError => {
  // 自定义发送请求失败逻辑,断网,请求发送监控等

  return Promise.reject(requestError)
}

/**
 * 拦截器响应请求成功
 *
 * @export
 * @param {*} responseObj
 * @returns
 */
export const responseSuccess = responseObj => {
  if (responseObj.headers && responseObj.headers['x-perm-id']) {
    localStorage.setItem('x-perm-id', responseObj.headers['x-perm-id'])
  }
  if (
    responseObj.data.code === 113002 ||
    responseObj.data.code === 113003 ||
    responseObj.data.code === 113006
  ) {
    router.replace({
      name: 'loginError'
    })
  }
  return responseObj.data
}

/**
 * 拦截器响应请求失败
 *
 * @export
 * @param {*} responseError
 * @returns
 */
export const responseFail = responseError => {
  // 响应失败,可根据 responseError.message 和 responseError.response.status 来做监控处理

  return Promise.reject(responseError)
}
  • 使用
// 接口统一处理
tagbind ({ data, ...rest }) {
    return request({ url: 'services/v3/charge/crm/tagbind', 'Content-Type': 'application/json;charset=utf-8', data, ...rest })
  },
// 接口页面传参
this.$api.tagbind({ data: { tagIds: tagIds, stationCode: this.$storage.get('stationCode') } }).then(res => {
        if (res.code === 200) {
          this.$toast('保存成功!')
          setTimeout(() => {
            this.$router.replace({ name: 'stationDetail' })
          }, 2000)
        }
      })

你可能感兴趣的:(axios进行封装,可自定义loading及Error提示等功能)