http.js 2.38 KB
/**
 * axios 全局配置
 */

import axios from 'axios'
import vue from 'vue'
import router from '../router'
const service = axios.create({
  timeout: 2000000 //设置请求超时时间
})


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

let loading        //定义loading变量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

/**@param
 * 请求前的拦截器
 */
service.interceptors.request.use(function (config) {
  const token = localStorage.getItem('atoken');
  //截取API添加时间戳防止请求缓存
  if (config.method == "get") {
    config.params = {
      _t: Date.parse(new Date()) / 1000,
      ...config.params
    };
  }
  if (config.url.indexOf('codes/countries') < 1) {
    if (config.url.indexOf('cates') < 1) {
      if (token) {
        // config.headers.authorization = '4db5183a-721b-4eee-b623-1d143890e813';
        config.headers.authorization = token;
        //showFullScreenLoading();
      } else {
        router.push('/');
      }
    }
  }
  return config
}, function (err) {
  //tryHideFullScreenLoading();
});


/**
 * @param
 * 响应前的拦截器
 */
service.interceptors.response.use(function (res) {
  //tryHideFullScreenLoading();
  if (res.data) {
    if (res.data.ecode === 401) {
      Message({
        type: 'error',
        message: res.data.enote
      })
      // router.push('/');
    }
  }
  return res;
}, function (err) {
  //tryHideFullScreenLoading();
  return Promise.reject(err);
})

export default service