|
| 1 | +console.log('4.2-fetch-api-advanced.js loaded'); |
| 2 | + |
| 3 | +// get buttons from html/DOM |
| 4 | +const getButton = document.getElementById('getButton'); |
| 5 | +const postButton = document.getElementById('postButton'); |
| 6 | + |
| 7 | +// common function to send receive http call |
| 8 | +const fn_sendhttpRequest = (httpMethod, httpUrl, data) => { |
| 9 | + |
| 10 | + return fetch(httpUrl, { |
| 11 | + method: httpMethod, |
| 12 | + body: JSON.stringify(data), |
| 13 | + headers: data ? {'Content-type': 'application/json'} : {} |
| 14 | + }).then(respenseResult => { |
| 15 | + console.log('respenseResult:', respenseResult); |
| 16 | + if (respenseResult.status >= 400) { |
| 17 | + return respenseResult.json().then(errResponseData => { |
| 18 | + const error = new Error('Please verify...something went wrong!'); |
| 19 | + error.data = errResponseData; |
| 20 | + throw error; |
| 21 | + }) |
| 22 | + } |
| 23 | + // to convert response body: ReadableStream to json |
| 24 | + return respenseResult.json(); |
| 25 | + }) |
| 26 | + |
| 27 | +} |
| 28 | + |
| 29 | +// define function to get data |
| 30 | +const fn_getData = () => { |
| 31 | + console.log('getButton clicked - in fn_getData'); |
| 32 | + |
| 33 | + fn_sendhttpRequest('GET', 'https://reqres.in/api/users') |
| 34 | + .then(respenseResultData => { |
| 35 | + console.log('respenseResultData:', respenseResultData); |
| 36 | + |
| 37 | + document.getElementsByClassName('user-name')[0].innerHTML = respenseResultData.data[0].first_name + ' ' + respenseResultData.data[0].last_name; |
| 38 | + document.getElementsByClassName('user-email')[0].innerHTML = respenseResultData.data[0].email; |
| 39 | + document.getElementsByClassName('user-image')[0].src = respenseResultData.data[0].avatar; |
| 40 | + }); |
| 41 | + |
| 42 | +} |
| 43 | + |
| 44 | +// define function to post/send data |
| 45 | +const fn_postData = () => { |
| 46 | + console.log('postButton clicked - in fn_postData'); |
| 47 | + |
| 48 | + const postLoginData = { |
| 49 | + email: "eve.holt@reqres.in", |
| 50 | + password: "pistol" |
| 51 | + }; |
| 52 | + |
| 53 | + fn_sendhttpRequest('POST', 'https://reqres.in/api/register', postLoginData) |
| 54 | + .then(respenseResultData => { |
| 55 | + console.log('respenseResultData:', respenseResultData); |
| 56 | + }) |
| 57 | + .catch(err => { |
| 58 | + console.error('Request failed', err) |
| 59 | + }) |
| 60 | + |
| 61 | +} |
| 62 | + |
| 63 | +// add event listener to button |
| 64 | +getButton.addEventListener('click', fn_getData); |
| 65 | +postButton.addEventListener('click', fn_postData); |
0 commit comments