import axios from 'axios'
import store from 'store'
import { Loading, Message } from 'element-ui'
//创建loading实例变量
let loadingInstance = null;
//创建自定义axios实例
const server = axios.create({
baseURL: '/',
timeout: 30000
});
//创建请求拦截器,可以再发送请求之前做些处理
server.interceptors.request.use(config => {
return config;
},error => {
return Promise.reject(error)
})
//创建响应拦截器,在响应被then方法执行之前做处理
server.interceptors.response.use(response => {
return response.data
},error => {
return Promise.reject(error)
})
const httpServer = (options) =>{
//http请求参数设置
let httpOpts = {
method: options.method,
url: options.url,
params: options.params,
data: options.data
};
//是否要加Loading处理
let increaseLoadingNum = () => {
if(options.showLoading){
store.dispatch('IncreaseLoadingNum').then(() => {
//如果增加完之后做处理在这里扩展
loadingInstance || (() => {
loadingInstance = Loading.service({
fullscreen: true,
text: "拼命加载中"
})
})()
})
}
};
//是否要取消Loading处理
let decreaseLoadingNum = () => {
if(options.showLoading){
store.dispatch('DecreaseLoadingNum').then(() => {
//如果减完之后做处理在这里扩展
if(store.state.fetchLoading.fetchLoadingNum == 0){
loadingInstance && (() => {
loadingInstance.close();
loadingInstance = null;
})()
}
})
}
};
//用promise包装一下axios请求
let httpPromise = new Promise((resolve,reject) => {
increaseLoadingNum();
server(httpOpts).then((data) => {
decreaseLoadingNum();
if(data.result== '1' || (data.data && (data.data.result == 1 || data.data.result == '003'))){
resolve(data);
}else if(data.result== '0'||(data.data && (data.data.result == 0||data.data.result == '004'||data.data.result == '005'))){
Message({
message: data.message||data.data.message,
type: 'warning'
})
reject(data)
}
}).catch((error) => {
let msg="服务器请求失败或超时";
if(error.request.status=='403'){
msg="抱歉,您没有访问权限.";
}
decreaseLoadingNum();
Message({
message: msg,
type: 'error'
})
reject(error);
})
})
return httpPromise;
}
export default httpServer