vue axios请求全局配置返回提示信息&且全局配置加载loading

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Loading } from 'element-ui';


//开始加载动画
let loading;
let loadingFlag = false;
function startLoading() {
  loadingFlag = true;
  loading = Loading.service({
    // target: '.main-container',

    text:'拼命加载中...',//加载中需要显示的文字
    background:'rgba(0,0,0,.7)',//背景颜色

  });
}
//结束加载动画
function endLoading() {
  loading.close();
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API + '/api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.Authorization) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken();
      startLoading();
      // 判断当前请求是否设置了不显示Loading
      if(config.headers.showLoading !== false){
        startLoading();//请求时的加载动画
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code != 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 10 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code == "1003") {
        // to re-login
        MessageBox.confirm(res.msg, {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      if(loadingFlag){
        endLoading();
      }
    } else {
      if(loadingFlag){
        endLoading();
      }
      return res
    }

  },
  error => {
    if(loadingFlag){
      endLoading();
    }
    console.log('err' + error) // for debug
    // 判断请求异常信息中是否含有超时timeout字符串
    if(error.message.includes('timeout')){
      Message({
        message: '请求超时',
        type: 'error',
        duration: 5 * 1000
      })
    }else if(error.response.status == '502'){
      Message({
        message: '网关错误',
        type: 'error',
        duration: 5 * 1000
      })
    }else if(error.response.status == '500'){
      Message({
        message: '服务器错误,请联系管理员',
        type: 'error',
        duration: 5 * 1000
      })
    } else{
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error);
    }
    // return Promise.reject(error)
  }
)

export default service
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值