-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.js
More file actions
95 lines (90 loc) · 2.49 KB
/
Copy pathrequest.js
File metadata and controls
95 lines (90 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import axios from "axios";
// axios.defaults.withCredentials = true;
axios.defaults.baseURL = "/api";
// axios.defaults.baseURL = "http://139.9.103.141:666";
import { useOpenNotification } from "@/hooks/myHooks"
const instance = axios.create({
baseURL: "/api",
withCredentials: true,
});
instance.interceptors.request.use(
//请求之前 设置请求信息 请求拦截器
function (config) {
return config; //必须返回config
},
//请求前拦截器异常方法
function () {
return Promise.reject("请求失败");
}
);
instance.interceptors.response.use(
//响应码为200要执行的方法
(response) => {
response.aa = 123; //给响应的数据添加属性
return response;
},
//处理响应码不是200的方法
(error) => {
useOpenNotification(error,false)
return Promise.reject("响应失败");
}
);
function fileChange(res,fileName) {
let blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
let downloadElement = document.createElement("a");
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
let nameArr = res.request.responseURL.split("/");
let nameStr = nameArr[nameArr.length - 1];
if(fileName!=null){
downloadElement.download = decodeURIComponent(fileName); //下载后文件名
}else {
downloadElement.download = decodeURIComponent(nameStr); //下载后文件名
}
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
const request = {
get(url = "", params = {}, headers = {}, responseType = "json") {
return instance({
method: "GET",
url,
params,
headers,
responseType,
});
},
post(url = "", data = {}, headers = {}) {
return instance({
method: "POST",
url,
data,
headers,
});
},
uploadFile(url = "", data) {
return instance({
headers: {
'Content-Type': 'multipart/form-data'
},
method: "POST",
url,
data,
});
},
download(url) {
return instance.get(url, {responseType: "blob"}).then((res) => {
console.log(res);
fileChange(res);
});
},
downloadPost(url, data = {},fileName) {
return instance.post(url, data, {responseType: "blob"}).then((res) => {
console.log(res);
fileChange(res,fileName);
});
},
};
export default request;