-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml_http.js
50 lines (46 loc) · 1.45 KB
/
xml_http.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
function fetchPics() {
const url = 'https://picsum.photos/list';
const init = { method: 'GET' };
const request = new Request(url, init);
fetch(request).then((response) => {
if (!response) throw new Error(response);
return response.json();
}).then(json => {
console.log(json);
}).catch(error => console.warn(`Error fetching pics ${ error }`));
}
// Uncomment below to fetch pics
// fetchPics();
function xmlRequestThing(args) {
const { method, url, headers } = args;
const xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.open(method, url);
// Headers can be received as an object containing all headers
// here we can iterate through them and set them with setRequestHeader()
if (headers) {
const keys = Object.keys(headers);
for (let i = 0; i < keys.length; i++) {
xhr.setRequestHeader(keys[i], headers[keys[i]]);
}
}
xhr.onload = () => {
const response = JSON.parse(xhr.response);
if (response.error) reject(`ERROR: ${ response.error }`);
resolve(response);
}
xhr.onerror = (error) => reject(`ERROR: ${ error.statusText }`);
xhr.send();
});
}
function runXMLDemo() {
const picsPayload = {
method: 'GET',
url: 'https://picsum.photos/list',
};
xmlRequestThing(picsPayload)
.then((response) => console.log(response))
.catch((error) => console.warn(error));
}
// Uncomment below to do the XMLHttpRequest thing
// runXMLDemo();