-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.html
113 lines (103 loc) · 2.78 KB
/
test.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var baseUrl = 'http://localhost:4201';
var qs = {
stringify: params => {
var arr = [];
Object.keys(params).forEach(k => {
arr.push(`${k}=${params[k]}`);
});
return arr.join('&');
},
};
function print(xhr) {
switch (xhr.responseType) {
case 'json':
console.log(
`${xhr.responseURL}:`,
JSON.stringify(xhr.response, null, 2)
);
return;
case 'text':
default:
console.log(`${xhr.responseURL}:`, xhr.response);
}
}
function request({
method = 'GET',
url,
headers,
responseType = 'json',
params,
}) {
var xhr = new XMLHttpRequest();
var src = `${baseUrl}${url}`;
if (params) {
switch (method.toUpperCase()) {
case 'GET':
case 'DELETE':
params = qs.stringify(params);
src += `?${params}`;
break;
case 'POST':
case 'PUT':
// json
if (headers && headers['content-type'].indexOf('json') > -1) {
params = JSON.stringify(params);
break;
}
// 非 json
if (!headers) headers = {};
headers['content-type'] = 'application/x-www-form-urlencoded';
params = qs.stringify(params);
break;
}
}
xhr.responseType = responseType;
xhr.open(method, src, true);
if (headers) {
Object.keys(headers).forEach(k => {
xhr.setRequestHeader(k, headers[k]);
});
}
xhr.send(params);
return new Promise(resolve => {
xhr.onload = () => {
resolve(xhr);
};
});
}
request({
url: '/api/example',
params: { delay: 5000 },
}).then(print);
request({
url: '/static/test/bird.svg',
responseType: 'text',
})
.then(xhr => {
document.body.innerHTML = xhr.responseText;
return xhr;
})
.then(print);
request({
url: '/diy/rawResponse',
responseType: 'text',
}).then(print);
request({
url: '/ipa/example',
method: 'POST',
headers: { 'content-type': 'application/json' },
params: { c: 3, d: 4 },
}).then(print);
</script>
</body>
</html>