axios.js 1.57 KB
import axios from 'axios'
import store from '../store/index.js'

import {Message,Loading} from 'element-ui'
let loading;
//内存中正在请求的数量
let loadingNum=0;
function startLoading() {    
	if(loadingNum==0){
		loading = Loading.service({
		  lock: true,
		  text: '拼命加载中...',
		  background:'rgba(255,255,255,0.5)',
		})
	}
	//请求数量加1
	loadingNum++;
}
function endLoading() {
    //请求数量减1
	loadingNum--
	if(loadingNum<=0){
		loading.close()
	}
}
// 创建 axios 实例
let service = axios.create({
  // headers: {'Content-Type': 'application/json'},
  timeout: 60000
})



// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
	  if (store.state.users.atoken) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
		  config.headers.authorization = store.state.users.atoken;
	  }
	 if (config.method == 'get') {
	   config.params = {
		  _t: Date.parse(new Date()) / 1000,
		 ...config.params
	   }
	 }
	 startLoading();
	return config
  },
  (err) => {
    // 请求错误处理
    return Promise.reject(err)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
	endLoading();
    let { data } = response
    return data
  },
  (err) => {
	endLoading();
	 if (err && err.response) {
		 Message.error({message: err.response.data.enote});
			 
    }else{
		Message.error({message:  '连接服务器失败!'});
    }
	return Promise.reject(err)
  }
)

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function() {
  return service
}