CustomTokenInterceptor.ts
7.33 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import {AxiosInstance} from 'axios';
import {message} from 'ant-design-vue';
import {AuthenticationManager} from "autumn-vue/lib/core/security/AuthenticationManager";
import {DefaultTokenInterceptor} from "autumn-vue/lib/core/http/DefaultTokenInterceptor";
import {AutumnConfig} from "autumn-vue/lib/core/config/AutumnConfig";
import dayjs, {Dayjs} from "dayjs";
export class CustomTokenInterceptor {
public static readonly AUTHORIZATION = 'Authorization';
constructor(public axios: AxiosInstance, public authService: AuthenticationManager) {
// 初始化拦截器
this.initInterceptors();
}
/**
* 初始化拦截器
*/
private initInterceptors(): void {
/**
* 请求拦截器
* 每次请求前,如果存在token则在请求头中携带token
*/
this.axios.interceptors.request.use(
(config: any) => {
// 登录流程控制中,根据本地是否存在token判断用户的登录情况
// 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
// 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
const authToken = this.authService.getToken();
if (authToken) {
config.headers.Authorization = 'Bearer ' + authToken;
}
if (config.method === 'post' && config.data) {
// post请求加上spinning样式,防止重复提交
if (config.url.indexOf('/page') === -1) {
}
config.data = this.recursivelyFormatTime(config.data, 0);
}
return config;
},
(error: any) => {
this.handleError(error);
return Promise.reject(error);
},
);
// 响应拦截器
this.axios.interceptors.response.use(
// 请求成功
(res: any) => {
if (res.status === 200) {
if (res.headers) {
const resToken = res.headers[DefaultTokenInterceptor.AUTHORIZATION];
if (resToken) {
this.authService.updateToken(resToken);
}
}
return Promise.resolve(res);
} else {
this.handleError(res);
return Promise.reject(res);
}
},
// 请求失败
(error: any) => {
if (error) {
// 请求已发出,但是不在2xx的范围
this.handleError(error);
return Promise.reject(error.response);
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
// this.showMessage('网络连接异常,请稍后再试!');
}
});
}
/**
* 递归处理时间字段的函数
* @param obj
* @param key
*/
recursivelyFormatTime(obj, level: number, key?: string) {
if (level > 5) {
return obj;
}
level++;
// if (obj instanceof Date) {
// // 如果对象是日期类型,格式化它
// return this.formatTime(obj);
// } else
if (this.isDayjsObject(obj)) {
return this.formatTime(obj, key);
} else if (typeof obj === 'object') {
// 如果对象是复杂对象,递归遍历它的属性
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
obj[key] = this.recursivelyFormatTime(obj[key], level, key);
}
}
}
return obj;
}
/**
* 判断对象是否为dayjs类型
* @param obj
*/
isDayjsObject(obj) {
return dayjs.isDayjs(obj);
}
/**
* 格式化时间的函数
* @param time
* @param key
*/
formatTime(time: Dayjs, key?: string) {
// 在这里执行时间格式化操作,使用合适的日期库,例如moment.js、date-fns等
// 示例:使用date-fns格式化时间
if (key && key.endsWith("Date")) {
const formattedTime = time.format('YYYY-MM-DD');
return formattedTime;
} else {
const formattedTime = time.format('YYYY-MM-DD HH:mm');
return formattedTime;
}
}
/**
* http握手错误
* @param error 响应回调,根据不同响应进行不同操作
*/
private handleError(error: any) {
if(!error.response){
return;
}
console.log(error);
// 状态码判断
const status = error.response?.status;
const errorResponse = error.response?.data;
const statusText = error.response.statusText;
let msg;
let type = 'error';
switch (status) {
case 400:
msg = '请求错误(400)';
if (errorResponse) {
if (typeof errorResponse === 'string') {
msg = errorResponse;
} else if (typeof errorResponse === 'object') {
msg = errorResponse.message;
} else {
msg = statusText;
}
}
break;
case 401:
type = 'warning';
msg = '未授权,请重新登录(401)'
break
case 403:
msg = '拒绝访问(403)'
break
case 404:
msg = AutumnConfig.ERROR_404_HINT
break
case 408:
msg = '请求超时(408)'
break
case 500:
msg = AutumnConfig.ERROR_500_HINT
break
case 501:
msg = '服务未实现(501)'
break
case 502:
msg = '网络错误(502)'
break
case 503:
msg = '服务不可用(503)'
break
case 504:
msg = '网络超时(504)'
break
case 505:
msg = 'HTTP版本不受支持(505)'
break
case 0:
msg = '无法连接到服务器,请检测您的网络'
break
default:
msg = `连接出错(${status})!`
}
this.showMessage(type, msg, status);
}
/**
* 处理请求失败事件
* @ param type
* @ param msg
*/
/**
* 处理请求失败事件
* @ param type
* @ param msg
*/
showMessage(type: string, msg: string, status: string): void {
if (msg) {
if (type === 'error') {
message.error(msg, 6);
} else {
message.warning(msg, 5);
}
}
if (status == '401') {
window.location.href = '/login';
}
}
}