-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch.js
53 lines (44 loc) · 1.46 KB
/
fetch.js
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
window.fetch = window.fetch || function (url, options) {
options = options || {};
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open(options.method || 'get', url);
for (let i in options.headers) {
request.setRequestHeader(i, options.headers[i]);
}
request.withCredentials = options.credentials == 'include';
request.onload = () => {
resolve(response());
};
request.onerror = reject;
request.send(options.body);
function response() {
let keys = [],
all = [],
headers = {},
header;
request.getAllResponseHeaders().replace(/^(.*?):\s*([\s\S]*?)$/gm, (m, key, value) => {
keys.push(key = key.toLowerCase());
all.push([key, value]);
header = headers[key];
headers[key] = header ? `${header},${value}` : value;
});
return {
ok: (request.status / 200 | 0) == 1, // 200-299
status: request.status,
statusText: request.statusText,
url: request.responseURL,
clone: response,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(request.responseText).then(JSON.parse),
blob: () => Promise.resolve(new Blob([request.response])),
headers: {
keys: () => keys,
entries: () => all,
get: n => headers[n.toLowerCase()],
has: n => n.toLowerCase() in headers
}
};
}
});
}