-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathfetchAxios.js
More file actions
142 lines (119 loc) · 4.61 KB
/
fetchAxios.js
File metadata and controls
142 lines (119 loc) · 4.61 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
import FormData from 'form-data';
import https from "https";
class FetchAxios {
constructor(defaultConfig = {}) {
this.defaults = {
baseURL: '',
headers: {},
timeout: 0,
responseType: 'json', // json, text 或 arraybuffer
withCredentials: false,
httpsAgent: null,
...defaultConfig,
};
this.interceptors = {request: [], response: []};
}
useRequestInterceptor(fn) {
this.interceptors.request.push(fn);
}
useResponseInterceptor(fn) {
this.interceptors.response.push(fn);
}
async request(urlOrConfig, config = {}) {
let finalConfig = {};
// 判断调用方式
if (typeof urlOrConfig === 'string') {
finalConfig = {...this.defaults, ...config, url: this.defaults.baseURL + urlOrConfig};
} else {
finalConfig = {...this.defaults, ...urlOrConfig, url: this.defaults.baseURL + (urlOrConfig.url || '')};
}
// 执行请求拦截器
for (const interceptor of this.interceptors.request) {
finalConfig = await interceptor(finalConfig) || finalConfig;
}
// 拼接 params
if (finalConfig.params) {
const query = new URLSearchParams(finalConfig.params).toString();
finalConfig.url += (finalConfig.url.includes('?') ? '&' : '?') + query;
}
const controller = new AbortController();
if (finalConfig.timeout) setTimeout(() => controller.abort(), finalConfig.timeout);
const fetchOptions = {
method: (finalConfig.method || 'GET').toUpperCase(),
headers: {...finalConfig.headers},
signal: controller.signal,
credentials: finalConfig.withCredentials ? 'include' : 'same-origin',
agent: finalConfig.httpsAgent || undefined,
};
if (finalConfig.data instanceof FormData) {
fetchOptions.body = finalConfig.data;
Object.assign(fetchOptions.headers, finalConfig.data.getHeaders());
} else if (finalConfig.data) {
if (typeof finalConfig.data === 'object' && !fetchOptions.headers['Content-Type']) {
fetchOptions.headers['Content-Type'] = 'application/json';
}
fetchOptions.body = fetchOptions.headers['Content-Type'] === 'application/json'
? JSON.stringify(finalConfig.data)
: finalConfig.data;
}
try {
const response = await fetch(finalConfig.url, fetchOptions);
let responseData;
if (finalConfig.responseType === 'json') {
responseData = await response.json().catch(() => null);
} else if (finalConfig.responseType === 'arraybuffer') {
responseData = await response.arrayBuffer();
} else {
responseData = await response.text();
}
let result = {
data: responseData,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
config: finalConfig,
request: finalConfig.url,
};
for (const interceptor of this.interceptors.response) {
result = await interceptor(result) || result;
}
if (!response.ok) throw result;
return result;
} catch (err) {
throw err;
}
}
get(url, config) {
return this.request(url, {...config, method: 'GET'});
}
post(url, data, config) {
return this.request(url, {...config, method: 'POST', data});
}
put(url, data, config) {
return this.request(url, {...config, method: 'PUT', data});
}
delete(url, config) {
return this.request(url, {...config, method: 'DELETE'});
}
}
// 创建 axios 实例函数
export function createInstance(defaultConfig) {
const context = new FetchAxios(defaultConfig);
// 创建可调用函数
const instance = context.request.bind(context);
// 挂载方法
['get', 'post', 'put', 'delete', 'useRequestInterceptor', 'useResponseInterceptor'].forEach(method => {
instance[method] = context[method].bind(context);
});
return instance;
}
// 忽略 HTTPS 证书错误
export const httpsAgent = new https.Agent({rejectUnauthorized: false});
export function createHttpsInstance() {
return createInstance({
headers: {'User-Agent': 'Mozilla/5.0'},
timeout: 10000,
responseType: 'arraybuffer',
httpsAgent: httpsAgent
});
}