-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhr.ts
72 lines (64 loc) · 2.33 KB
/
xhr.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
import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from './types'
import { parseHeaders } from './helpers/header'
import { resolve } from 'url';
import { createError } from './helpers/error'
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
const {data = null, url, method = 'get', headers, responseType, timeout} = config;
const request = new XMLHttpRequest();
if(responseType) {
request.responseType = responseType
}
if(timeout) {
request.timeout = timeout
}
if (request.status === 0) {
return
}
request.open(method.toUpperCase(), url, true);
request.ontimeout = function handleTimeout() {
reject(
// createError(`Timeout of ${config.timeout} ms exceeded`, config, 'ECONNABORTED', request)
new Error('timeout')
)
}
request.onreadystatechange = function handleLoad () {
if (request.readyState !==4) {
return
}
const responseHeaders = parseHeaders(request.getAllResponseHeaders())
const responseData = responseType !== 'text' ? request.response : request.respnseTest
const response: AxiosResponse = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
}
resolve(response);
}
request.onerror = function handleError() {
reject(new Error('Network Error'))
}
if(headers) {
Object.keys(headers).forEach((name) => {
if(data === null && name.LowerCase() === 'content-type'){
delete headers[name]
} else {
request.setRequestHeader(name, headers[name])
}
})
}
request.send(data);
function handleResponse(response: AxiosResponse): void {
if (response.status >= 200 && response.status < 300) {
resolve(response)
} else {
reject(
new Error('wrong status')
)
}
}
})
}