Vue自用axios封装

[本文出自天外归云的博客园]

这是我的Vue项目中的request.js文件,请求报错了看console就会有具体请求信息,方便调试。分享一下。

其中用到了axios和element-ui的组件,axios是用来收发请求的,element-ui中的Message和Loading组件主要是配合axios对请求中和请求失败的情况在页面上进行可视化配合。

代码如下:

import axios from 'axios'
import { Message, Loading } from 'element-ui'

let loading
let needLoadingRequestCount = 0

function startLoading () {
  loading = Loading.service({
    lock: true
  })
}

export function showLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function hideLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    loading.close()
  }
}

const instance = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 150000,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
})

instance.interceptors.request.use(
  function (config) {
    console.log('[发起请求]' + JSON.stringify(config.data))
    showLoading()
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  response => {
    const res = response.data
    if (res.retcode !== 200) {
      // Message({
      //   message: '[接口返回非200异常]请重新刷新页面',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      hideLoading()
      return Promise.reject(new Error('返回非200')).catch(
        console.log('[请求]' + response.config.data + '
[返回异常]' + res)
      )
    } else if (JSON.stringify(res.data) === '{}') {
      return Promise.reject(new Error('no data'))
        .then(result => console.log(result))
        .catch(error => console.log(error))
    } else {
      hideLoading()
      return res.data
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error).catch(console.log(error))
  }
)

export default instance

 其中process.env在config/dev.env.js中定义:

原文地址:https://www.cnblogs.com/LanTianYou/p/10526014.html