axios.js
2.66 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
/*
* @Date: 2023-10-27 11:12:24
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2023-12-04 10:24:48
* @FilePath: /vue-flow-editor/doc/axios.js
* @Description: 文件描述
*/
import axios from 'axios';
import { ElMessageBox } from 'element-plus'
axios.defaults.params = {
m: 'mod',
p: 'authority_my',
};
const parseQueryString = url => {
var json = {};
var arr = url.indexOf('?') >= 0 ? url.substr(url.indexOf('?') + 1).split('&') : [];
arr.forEach(item => {
var tmp = item.split('=');
json[tmp[0]] = decodeURIComponent(tmp[1]);
});
return json;
}
// 获取CancelToken
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
/**
* @description 请求拦截器
*/
axios.interceptors.request.use(
config => {
// const url_params = parseQueryString(location.href);
// GET请求默认打上时间戳,避免从缓存中拿数据。
const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
/**
* POST PHP需要修改数据格式
* 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
*/
// 绑定默认请求头
config.params = { ...config.params, timestamp };
// 全局添加cancelToken
config.cancelToken = source.token;
return config;
},
error => {
// 请求错误处理
return Promise.reject(error);
});
/**
* @description 响应拦截器
*/
axios.interceptors.response.use(
response => {
// 默认显示错误提示
// response.data.show = true;
if (response.data.msg === '登录失效') {
// TAG: 某个请求的响应满足特定条件的情况下,取消【其他正在进行的请求】
source.cancel();
//
ElMessageBox.alert('登录失效!将跳转到登录页面。', '温馨提示', {
confirmButtonText: '确定',
callback: action => {
// session 失效需要重新登录
if (action === 'confirm') {
localStorage.setItem('showConfirmation', '0');
// 拼接跳转地址,因为要返回到当前页面传入参数
let url_params = parseQueryString(location.href);
let str = `/admin/custom_flow/?form_id=${url_params.form_id}`;
window.location.href = location.origin + '/admin/' + window.location.search + `&refer_url=${encodeURIComponent(str)}`;
}
}
});
}
return response;
},
error => {
if (axios.isCancel(error)) { // 取消请求的情况下,终端Promise调用链
return new Promise(() => {
console.error('取消请求响应', error);
});
} else {
return Promise.reject(error);
}
});
export default axios;