In an attempt to get rid of Ajax calls I have changed my code to use the Javascript Fetch API which is very clean.
In the example below, I had to comment out the body
fetch option of the request as well as change the method option to GET
.
I did this to see if it would work and.. it did.
Now I am wondering how am I going to pass the body
fetch option params to the request.
Lastly, I have run into something called AbortController Interface and would like to know if you can show me how to implement it in this sample below or if it cannot benefit from it at all.
Thank you
// POST DATA
function postData(url = 'https://api.myjson.com/bins/elr1f', params = [{param1Key: 'param1Val'}]) {
const fetchOptions = {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
'Content-Type': 'application/json',
// 'Content-Type', 'text/xml'
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
// body: JSON.stringify(params), // body data type must match "Content-Type" header
};
// Default fetchOptions are marked with *
return fetch(url, fetchOptions)
.then(function(response) {
// RESPONSE VALIDATION
switch (response.status) {
case 200:
// code...
console.info('HTTP response status: 200 OK');
return response;
break;
case 404:
// code...
throw new Error('HTTP response status: 404 Not Found.');
break;
case 500:
// code...
throw new Error('HTTP response status: 500 Internal Server Error.');
break;
case 503:
// code...
throw new Error('HTTP response status: 503 Service Unavailable.');
break;
default:
// code...
break;
}
})
// parse JSON response into native JavaScript object(s)
.then (response => response.json() )
// access the node we want
.then (response => console.info(response.users) )
// catch a freaking error
.catch(error => console.error(error) );
}
<button onclick="postData()">GET USERS</button>