http.ts
2.56 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
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import createError, { createErrorByError, ErrorMsg } from './createError';
import { IndexLogin } from 'client/components/BottomBar/entity';
// @ts-ignore
import each from 'lodash/each';
interface req extends AxiosRequestConfig {
requestType?: 'JSONString' | 'paramString' | 'formdata' | 'plainString';
hasToken?: boolean;
token?: string;
}
interface ExceptionHandle {
reload?: boolean;
}
/**
* 请求头信息拦截调整
*/
axios.interceptors.request.use(
async (config: req): Promise<req> => {
if (!config.timeout) {
config.timeout = 30 * 1000;
}
/**
* 给每个请求新增时间戳
*/
config.params = { _s: Date.now(), ...config.params };
if (config.token) {
config.headers.Authorization = config.token;
}
return config;
},
);
axios.interceptors.response.use(
(response): any => {
let data = response.data;
if (data) {
if (data.success === false) {
return createError(response as any);
}
if (Object.prototype.hasOwnProperty.call(data, 'data')) {
data.status = response.status;
return data;
}
return parseResponse(response);
}
return createError(response as any);
},
(error) => {
return createErrorByError(error);
},
);
export function get<T>(requestURL: string, config?: req): Promise<ICommon.ServerResponse<T>> {
// @ts-ignore
return axios.get(requestURL, config);
}
export function post<T>(requestURL: string, params: any, config?: req): Promise<ICommon.ServerResponse<T>> {
// @ts-ignore
return axios.post(requestURL, params, config);
}
/**
* 如果找不到response.data.data,则将返回格式解析为统一格式
*/
function parseResponse<T>(response: AxiosResponse): ICommon.ServerResponse<T> {
const code: number = response.status;
const success = true;
const result: string = response.statusText;
const status: number = response.status;
const data = response.data;
return { code, success, result, data, status };
}
function exceptionHandle(error: ErrorMsg, config?: ExceptionHandle) {
const code: number = Number(error.errorCode) || 0;
/**
* 用户未登陆
*/
if ([401, 40101, 40102, 40103, 40104].includes(code) && config && config.reload) {
// 跳转小程序登录
handleLoginPage();
}
}
const handleLoginPage = () => {
try {
const url = IndexLogin;
// @ts-ignore
wx.miniProgram.navigateTo({ url: `${url}?hasBack=0` });
} catch (e) {}
};
const http = {
get,
post,
exceptionHandle,
};
export default http;