axios.js
2.88 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
/*
* @Author: hookehuyr hookehuyr@gmail.com
* @Date: 2022-05-28 10:17:40
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-10-31 09:52:30
* @FilePath: /stdj_h5/src/utils/axios.js
* @Description:
*/
import axios from 'axios';
import { useLoadingStore } from '@/stores/loading.js'
// import router from '@/router';
// import qs from 'Qs'
// import { strExist } from '@/utils/tools'
// import { parseQueryString } from '@/utils/tools'
axios.defaults.params = {
f: 'stdj',
};
/**
* 安全调用全局loading store
* @param {string} method 方法名:'start' | 'end' | 'reset'
* @returns {void}
*/
function safe_loading(method) {
try {
const loading = useLoadingStore()
if (method === 'start') {
loading.start()
} else if (method === 'end') {
loading.end()
} else if (method === 'reset') {
loading.reset()
}
} catch (e) {
// 兜底:Pinia未就绪或Store未初始化时跳过
// 使用空操作避免空块,同时不打印控制台信息
void e
}
}
/**
* @description 请求拦截器
*/
axios.interceptors.request.use(
config => {
// 开始全局loading计数(安全封装),可通过config.ignore_loading禁用
if (!config || config.ignore_loading !== true) {
safe_loading('start')
}
// const url_params = parseQueryString(location.href);
// GET请求默认打上时间戳,避免从缓存中拿数据。
const timestamp = config.method === 'get' ? (new Date()).valueOf() : '';
/**
* POST PHP需要修改数据格式
* 序列化POST请求时需要屏蔽上传相关接口,上传相关接口序列化后报错
*/
// config.data = config.method === 'post' && !strExist(['a=upload', 'upload.qiniup.com'], config.url) ? qs.stringify(config.data) : config.data;
// 绑定默认请求头
config.params = { ...config.params, timestamp }
return config;
},
error => {
// 请求错误处理
// 出现错误时重置loading,避免长时间遮挡(安全封装)
if (!error || !error.config || error.config.ignore_loading !== true) {
safe_loading('reset')
}
return Promise.reject(error);
});
/**
* @description 响应拦截器
*/
axios.interceptors.response.use(
response => {
// 响应完成后减少计数
// 正常响应结束时减少pending计数,归零后关闭蒙版(安全封装)
if (!response || !response.config || response.config.ignore_loading !== true) {
safe_loading('end')
}
return response;
},
error => {
// 响应异常时直接重置隐藏loading
// 任一接口失败则关闭全局loading,交由页面/业务自行反馈错误(安全封装)
if (!error || !error.config || error.config.ignore_loading !== true) {
safe_loading('reset')
}
return Promise.reject(error);
});
export default axios;