-
Notifications
You must be signed in to change notification settings - Fork 3
/
Http.ts
89 lines (87 loc) · 2.61 KB
/
Http.ts
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
/**
* 请求工具
*/
import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { Modal, message } from 'antd';
import PageHistory from '@/router/PageHistory';
import mock from '@/module/mock/mock.module';
let isExpired = false;
export default class Http {
$http: AxiosInstance;
constructor() {
this.$http = axios.create({});
this.init();
}
init() {
this._defaultsConfig();
this._interceptRequest();
this._interceptResponse();
}
_defaultsConfig() {
this.$http.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
this.$http.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest';
this.$http.defaults.responseType = 'json';
this.$http.defaults.validateStatus = function (status) {
return true;
};
}
_interceptRequest() {
this.$http.interceptors.request.use(
(request) => request,
(error) => Promise.reject(error)
);
}
_interceptResponse() {
this.$http.interceptors.response.use(
(response) => {
if (response.status === 200 && response.data && response.data.code === 0) {
return Promise.resolve(response);
}
if (response.data && response.data.code === 1401) {
!isExpired &&
Modal.warning({
title: response.data.msg,
content: '',
onOk() {
isExpired = false;
localStorage.removeItem('isLogin');
PageHistory.push('/login');
},
});
isExpired = true;
return Promise.reject(response);
}
if (response.data && response.data.code === 1401) {
return Promise.reject(response);
}
if (response.data && response.data.code) {
message.error(response.data.msg);
return Promise.reject(response);
}
if (response.data && response.data.status) {
message.error('服务器异常');
}
if (!response.data) {
message.error('连接超时');
}
return Promise.reject(response);
},
(error) => {
message.error('数据拉取失败,请检查您的网络');
return Promise.reject(error);
}
);
}
get<T = any, R = AxiosResponse<T>>(url: string, params: any): Promise<R> | Promise<any> {
if((window as any).environment === 'dev') {
return mock(url)
}
return this.$http.get(url, params);
}
post<T = any, R = AxiosResponse<T>>(url: string, params: any): Promise<R> | Promise<any> {
if((window as any).environment === 'dev') {
return mock(url)
}
return this.$http.post(url, params);
}
}