import axios from 'axios'
class HttpRequest {
constructor(baseUrl = '') {
this.baseUrl = baseUrl
this.queue = {}
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
headers: {
}
}
return config
}
destroy(url) {
delete this.queue[url]
}
interceptors(instance, url) {
// 请求拦截
instance.interceptors.request.use(config => {
this.queue[url] = true
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截
instance.interceptors.response.use(res => {
this.destroy(url);
const {data, status} = res;
// 获取文件名
let fileName = res.config.fileName || res.headers['content-disposition'];
// 判断是否下载文件
if (fileName) {
fileName = decodeURIComponent(fileName);
const preStr = "attachment;filename*=UTF-8''";
const preStrTwo = "attachment;filename=";
if (fileName.startsWith(preStr)) {
fileName = fileName.substr(preStr.length);
} else if (fileName.startsWith(preStrTwo)) {
const split = fileName.split("=");
fileName = split[1];
}
let contentType = res.headers['content-type'];
if (contentType && contentType.indexOf(";") !== -1) {
contentType = contentType.substr(0, contentType.indexOf(";"));
}
let blob = new Blob([res.data], {type: contentType});
// 下载文件
if ('download' in document.createElement('a')) {
// 非IE下载
const a = document.createElement('a');
const downloadUrl = window.URL.createObjectURL(blob);
a.href = downloadUrl;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(downloadUrl);
} else {
// IE下载
navigator.msSaveBlob(blob, fileName);
}
return Promise.resolve("下载文件成功");
}
return {status, data};
}, error => {
this.destroy(url)
let errorInfo = error.response
if (!errorInfo) {
const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error))
errorInfo = {
statusText,
status,
request: {responseURL: config.url}
}
}
return Promise.reject(error);
});
}
request(options, isTranToFormData) {
let headers = {
...options.headers,
'Content-Type': 'application/json; charset=UTF-8',
}
// 下载文件
if (options.download) {
options.responseType = 'blob';
}
if (options.headers) {
for (let i in headers) {
for (let j in options.headers) {
if (j == i) {
headers[i] = options.headers[j];
} else {
headers[j] = options.headers[j];
}
}
}
}
const instance = axios.create({
headers: headers
})
options = {...this.getInsideConfig(), ...options};
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.data = bodyStr;
}
this.interceptors(instance, options.url)
return instance(options)
}
}
export default HttpRequest