import axios from ‘axios‘;
import router from ‘../../router‘;
import store from ‘../../store/index‘;
import Utils from ‘../utils/utils‘;
import { AES_encrypt, randomString } from ‘../config/encrypt‘;
import qs from ‘qs‘;
let [
body = document.getElementsByTagName(‘body‘)[0],
bg = document.createElement(‘section‘),
toast = document.createElement(‘section‘)
] = [];
//偏移量 由前端每次请求随机生成 16位
let IV = randomString(16);
//AES加密KEY 由前端自己每次请求随机生成
let KEY = randomString(16);
//公钥固定值
let pkcs8_public=‘-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCt5ugWm2WdqkMI5iDgTmdavYPTp6hmqbopy7N9fNnsNiwEE+toi0XgQjQeuE0Yf7VOIiCI8eWzUaTWfCK3D/dmFTbsTK3Ugql6QuYKRhSn9QnxtEqzvkz5jv3dc3sSav8gK3Ox22DBWUX5LOwY52kBieawlRFckv8vtCOYVPrd+wIDAQAB-----END PUBLIC KEY-----‘;
const CancelToken = axios.CancelToken;
let cancel;
// 防止重复请求
let removePending = (config) => {
for (let k in store.state[‘axiosPromiseCancel‘]) {
if (store.state[‘axiosPromiseCancel‘][k].u === config.url + ‘&‘ + config.method) { //当前请求在数组中存在时执行函数体
store.state[‘axiosPromiseCancel‘][k].f(); //执行取消操作
store.state[‘axiosPromiseCancel‘].splice(k, 1); //把这条记录从数组中移除
}
}
};
axios.defaults.baseURL = process.env.URL;
axios.defaults.timeout = 1000 * 60 * 3;
axios.defaults.headers.get[‘Content-Type‘] = ‘application/json‘;
axios.interceptors.request.use(
config => {
// 防止重复请求
removePending(config);
// console.log(config)
// 删除请求
config.cancelToken = new CancelToken((cancel) => {
store.state[‘axiosPromiseCancel‘].push({ u: config.url + ‘&‘ + config.method, f: cancel });
});
bg.className = ‘loading-bg‘;
bg.style.position = ‘fixed‘;
bg.style.zIndex = ‘99999‘;
bg.style.top = ‘0‘;
bg.style.left = ‘0‘;
bg.style.width = ‘100%‘;
bg.style.height = ‘100%‘;
bg.style.background = ‘rgba(0,0,0,0)‘;
toast.style.position = ‘absolute‘;
toast.style.top = ‘0‘;
toast.style.left = ‘50%‘;
toast.style.bottom = ‘0‘;
toast.style.margin = ‘auto 0‘;
toast.style.height = ‘.8rem‘;
toast.style.lineHeight = ‘.8rem‘;
toast.style.fontSize = ‘.3rem‘;
toast.style.transform = ‘translateX(-50%)‘;
toast.style.borderRadius = ‘.1rem‘;
toast.style.padding = ‘.1rem .3rem‘;
toast.style.whiteSpace = ‘nowrap‘;
toast.style.background = ‘rgba(0,0,0,.9)‘;
toast.style.color = ‘#fff‘;
toast.innerHTML = ‘<i class="fa fa-spinner fa-spin" style="font-size:.8rem;"></i>‘;
bg.appendChild(toast);
if (config[‘data‘] && window.isCryptData) {
config.headers[‘Content-Type‘] = ‘application/x-www-form-urlencoded; charset=UTF-8‘;
let enstr = AES_encrypt(JSON.stringify(config.data), KEY, IV, pkcs8_public);
config[‘data‘] = qs.stringify({data: enstr});
}
let url = config.url.substring(config.url.lastIndexOf(‘/‘) + 1);
// 不显示loading状态
let isHave = [
‘logo‘,
‘lotteryInfo‘,
‘availableIssues‘,
‘last-issue‘,
‘trace-issue-list‘,
‘exist-fund-password‘,
‘get-basic-content‘,
‘read-message‘,
‘is-crypt-data‘,
‘detail‘,
‘activity-list‘];
if (!isHave.includes(url)) {
body.appendChild(bg);
}
let token = Utils.storage.get(‘token‘);
if (token) {
config.headers.Authorization = ‘Bearer ‘ + token.data;
}
setTimeout(() => {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading) {
body.removeChild(loading)
}
}, 30000);
return config;
},
error => {
return Promise.reject(error);
});
axios.interceptors.response.use(
(response) => {
// 防止重复请求
removePending(response.config);
if (response[‘data‘][‘code‘] === 0) {
router.push(‘/login‘);
}
if (response.data && response.data.success) {
setTimeout(() => {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading) {
body.removeChild(loading)
}
}, 80);
return response.data
} else if (response.data.msg) {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading) {
toast.style.height = ‘.5rem‘;
toast.style.lineHeight = ‘.5rem‘;
toast.innerHTML = response.data.msg;
}
setTimeout(() => {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading) {
body.removeChild(loading)
}
}, 2500);
return []
}
}, (error) => {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading && error && error.msg) {
toast.innerHTML = error.response.data.msg;
}
if (error &&
error.response &&
error.response.status &&
(
error.response.status === 401 ||
error.response.status === 402 ||
error.response.status === 403 ||
error.response.status === 422
)) {
router.push(‘/login‘);
}
setTimeout(() => {
let loading = document.getElementsByClassName(‘loading-bg‘)[0];
if (loading) {
body.removeChild(loading)
}
}, 2500);
if (axios.isCancel(error)) {
// 为了终结promise链 就是实际请求 不会走到.catch(rej=>{});这样就不会触发错误提示之类了。
return new Promise(() => {
});
} else {
return Promise.reject(error);
}
});
let apiConfig = {
get(url, data) {
let enstr = null;
// let enstr = data ? AES_encrypt(JSON.stringify(data), KEY, IV, pkcs8_public) : null;
// 是否加密
if (data && window.isCryptData) {
enstr = {
data: AES_encrypt(JSON.stringify(data), KEY, IV, pkcs8_public)
}
} else if(data) {
enstr = data;
}
return new Promise((resolve, reject) => {
axios.get(url, {
params: enstr,
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
}).then((res) => {
resolve(res)
}).catch((error) => {
reject(error)
});
})
},
post(url, json) {
return new Promise((resolve, reject) => {
axios.post(url, json, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
}).then((res) => {
resolve(res)
}).catch((error) => {
reject(error)
})
})
}
};
export default apiConfig;
api---config.js