request.ts
2.78 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
/*
* @Author: yangming yangming@didihu.com.cn
* @Date: 2023-03-03 10:30:06
* @LastEditors: yangming yangming@didihu.com.cn
* @LastEditTime: 2023-03-17 11:25:12
* @FilePath: \achievements-system-front\src\api\request\request.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
// 以class类来实现axios实例化
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
// 自定义 promise interface
class HttpRequest {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
// 获取axios实例的配置
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
headers: {
"Content-Type": "application/json;charset=utf-8",
},
timeout: 1000 * 10,
};
return config;
}
// 设定拦截器
interceptors(instance: AxiosInstance) {
// 添加请求拦截器
instance.interceptors.request.use(
(config) => {
// 添加token
const token = sessionStorage.getItem("token") || "";
if (token) {
(config.headers as any).Authorization = "Bearer " + token;
}
// console.log('config:' + JSON.stringify(config))
// 在发送请求之前做些什么
return config;
},
(error: Error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
(response) => {
const code = response.data.code;
console.log(code);
// 对响应数据做点什么
if (code === 401) {
sessionStorage.clear();
window.location.replace("/login");
// 跟上边直接返回都是一样的(也可以不加Promise.resolve)
return Promise.resolve(response.data);
} else if ( response.status == 200) {
return Promise.resolve(response.data);
} else {
return Promise.reject(response);
}
},
(error: Error) => {
return Promise.reject(Error);
}
);
}
// 创建实例
request(options: AxiosRequestConfig) {
const instance = axios.create();
const newOptions = Object.assign(this.getInsideConfig(), options);
this.interceptors(instance);
return instance(newOptions);
}
get(url: string, config?: AxiosRequestConfig): Promise<HttpResponse> {
const options = Object.assign(
{
method: "get",
url: url,
},
config
);
return this.request(options);
}
post(url: string, data?: any): Promise<HttpResponse> {
return this.request({
method: "post",
url: url,
data: data,
});
}
}
export default HttpRequest;