-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfetch.js
37 lines (33 loc) · 1.02 KB
/
fetch.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
let getBtn = document.querySelector('.get-btn');
let sendBtn = document.querySelector('.send-btn');
let sendHttpRequest = (method, url, data) => {
return fetch(url, {
method,
body: JSON.stringify(data),
headers: data ? { 'Content-Type': 'application/json' } : {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errorResponseData => {
let error = new Error('Something went wrong');
error.data = errorResponseData;
throw error;
});
}
return response.json();
});
};
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, error.data));
};
getBtn.addEventListener('click', getData);
sendBtn.addEventListener('click', sendData);