-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxhr.js
49 lines (39 loc) · 1.25 KB
/
xhr.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
let getBtn = document.querySelector('.get-btn');
let sendBtn = document.querySelector('.send-btn');
let sendHttpRequest = (method, url, data) => {
let promise = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
// appending json data
if (data) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onload = () => {
if (xhr.status >= 400) {
reject(xhr.response);
} else {
resolve(xhr.response)
}
};
xhr.onerror = () => {
reject('Error occured!');
};
xhr.send(JSON.stringify(data));
});
return promise;
}
let getData = () => {
sendHttpRequest('GET', 'https://reqres.in/api/users')
.then(responseData => console.log(responseData));
};
let sendData = () => {
sendHttpRequest('POST', 'https://reqres.in/api/register', {
email: '[email protected]',
// password: 'pistol'
}).then((responseData) => {
console.log(responseData);
}).catch(error => console.log(error));
};
getBtn.addEventListener('click', getData);
sendBtn.addEventListener('click', sendData);