import axios from 'axios'
import {Message}from 'element-ui'
import router from '../router/permission'
import Vuefrom 'vue'
import VueCookiesfrom 'vue-cookies'
const moment =require('moment');
const Base64 =require('js-base64').Base64;
// loading框设置局部刷新,且所有请求完成后关闭loading框
var loading;
function startLoading() {
loading = Vue.prototype.$loading({
lock:true,
text:"Loading...",
target:document.querySelector('.loading-area')//设置加载动画区域
});
}
function endLoading() {
loading.close();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount =0;
function showFullScreenLoading() {
if (needLoadingRequestCount ===0) {
startLoading();
}
needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
if (needLoadingRequestCount <=0)return;
needLoadingRequestCount--;
if (needLoadingRequestCount ===0) {
endLoading();
}
};
// 请求拦截
axios.interceptors.request.use(config => {
let token ="";
showFullScreenLoading();
if(VueCookies.isKey('userinfo')) {
const USERINFO = VueCookies.get('userinfo');
if(config.method =='get') {
token =Base64.encode(USERINFO.token +'|' +moment().utc().format('YYY-MM-DD HH:mm:ss' +'|' +JSON.stringify(config.params)));
config.params.hospitalId =USERINFO.hospitalId;
}else {
token =Base64.encode(USERINFO.token +'|' +moment().utc().format('YYY-MM-DD HH:mm:ss' +'|' +JSON.stringify(config.data)));
config.data.hospitalId =USERINFO.hospitalId;
}
let TOKENSTART =token.slice(0,10),
TOKENEND =token.slice(10);
token =TOKENEND +TOKENSTART;
config.headers['token'] =token;
}
return config;
}, err => {
tryHideFullScreenLoading();
Message.error({message:'请求超时!' });
return Promise.resolve(err);
})
// 响应拦截
axios.interceptors.response.use(res => {
tryHideFullScreenLoading();
switch(res.data.code) {
case 200:
return res.data.result;
case 401:
router.push('/login');
VueCookies.remove('userinfo');
return Promise.reject(res);
case 201:
Message.error({message: res.data.msg });
return Promise.reject(res);
default :
return Promise.reject(res);
}
}, err => {
tryHideFullScreenLoading();
if(!err.response.status) {
return false;
}
switch(err.response.status) {
case 504:
Message.error({message:'服务器被吃了⊙﹏⊙∥' });
break;
case 404:
Message.error({message:'服务器被吃了⊙﹏⊙∥' });
break;
case 403:
Message.error({message:'权限不足,请联系管理员!' });
break;
default:
return Promise.reject(err);
}
})
axios.defaults.timeout =300000;// 请求超时5fen
export const postJsonRequest = (url, params) => {
return axios({
method:'post',
url: url,
data: params,
headers: {
'Content-Type':'application/json',
},
});
}
export const postRequest = (url, params) => {
return axios({
method:'post',
url: url,
data: params,
transformRequest: [function (data) {
let ret =''
for (let it in data) {
ret +=encodeURIComponent(it) +'=' +encodeURIComponent(data[it]) +'&'
}
return ret
}],
headers: {
'Content-Type':'application/x-www-form-urlencoded'
}
});
}
export const getRequest = (url, data ='') => {
return axios({
method:'get',
params: data,
url: url,
});
}
网友评论