forked from academind/xhr-fetch-axios-intro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xhr.js
52 lines (43 loc) · 1.16 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
50
51
52
const getBtn = document.getElementById('get-btn');
const postBtn = document.getElementById('post-btn');
const sendHttpRequest = (method, url, data) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json';
if (data) {
xhr.setRequestHeader('Content-Type', 'application/json');
}
xhr.onload = () => {
if (xhr.status >= 400) {
reject(xhr.response);
} else {
resolve(xhr.response);
}
};
xhr.onerror = () => {
reject('Something went wrong!');
};
xhr.send(JSON.stringify(data));
});
return promise;
};
const getData = () => {
sendHttpRequest('GET', 'https://reqres.in/api/users').then(responseData => {
console.log(responseData);
});
};
const sendData = () => {
sendHttpRequest('POST', 'https://reqres.in/api/register', {
email: 'eve.holt@reqres.in'
// password: 'pistol'
})
.then(responseData => {
console.log(responseData);
})
.catch(err => {
console.log(err);
});
};
getBtn.addEventListener('click', getData);
postBtn.addEventListener('click', sendData);