import axios from 'axios'
let axiosList = []
function pushAxios () {
//每次启动请求都添加数组
axiosList.push(1);
// 此处可以添加全局loading,防止还有接口为完成的时候用户误操作
showCover()
}
function popAxios () {
//接口有返回不管成功失败都要删除一个数组数据
axiosList.pop()
// 关闭全局loading
if (!axiosList.length) {
hideCover()
}
}
// 全局loading相关
function showCover(){}
function hideCover(){}
// 是否允许全局跨域cookie,原则上是不允许的
axios.defaults.withCredentials = false;
// axios请求拦截
axios.interceptors.response.use(
response => {
popAxios()
if (response.data !== null &&response.data.message !== undefined) {
// 判断(未登录,密码错误等)等状态
return Promise.reject(errorText)
}
return response
},
error => {
// 接口失败
popAxios()
return Promise.reject(errorText)
}
)
// 配置config
let baseURL;
let domain = document.domain;
if (domain == 'localhost') {//根据环境不同,配置不同的baseURL
baseURL = 'localhost'
}
let config = {
// 请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖掉config中的url
url: '/api',
// 请求方法同上
method: 'POST', // default
baseURL: baseURL,
hideWarning: false,
// 设置超时时间
timeout: 50000,
data: {},
// 返回数据类型
responseType: 'json',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json'
}
}
// 封装get,post等请求
class API extends Vue {
get (param) {
pushAxios()
config.url =param.url
config.data =param.data
if (param.baseURL) {config.baseURL =param.baseURL }
return axios.post(param.url, {}, config)
}
post (param) {
pushAxios()
config.url =param.url
config.data =param.data
config.headers['X-Token'] =localStorage.getItem('loginToken')
config.headers['Content-Type'] = 'application/json'
if (param.baseURL) {config.baseURL =param.baseURL }
if (param.responseType) {config.responseType =param.responseType }
let res = axios.post(param.url, {}, config)
config.responseType = 'json'
return res
}
// 下载excel文件
downLoadFileByBlob (res) {
const blob = new Blob([res.data], { type:res.headers['content-type'] })
let desprsitions =res.headers['content-disposition'].split(';')
let filename = ''
for (let i = 0; i <desprsitions.length; i++) {
if (desprsitions[i].indexOf('filename') > -1) {
let filenames =desprsitions[i].split('=')
if (filenames.length > 1) {
filename = decodeURI(filenames[1].trim())
}
}
}
if ('download' in document.createElement('a')) {
const downloadElement = document.createElement('a')
let href = ''
if (window.URL) href = window.URL.createObjectURL(blob)
else href = window.webkitURL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = filename
document.body.appendChild(downloadElement)
downloadElement.click()
if (window.URL) window.URL.revokeObjectURL(href)
else window.webkitURL.revokeObjectURL(href)
document.body.removeChild(downloadElement)
} else {
navigator.msSaveBlob(blob, filename)
}
}
}