There was a time when JavaScript Fetch API I requests were made using XMLHttpRequest. It lacked Promises and resulted in unclean JavaScript code. You could use the cleaner syntax of jQuery instead. ajax().
JavaScript now has its built-in method for making api requests. This is the Fetch api, a new standard for making server requests using Promises that includes extra features.
Fetch api to create GET and POST requests.
This task aims to demonstrate how to use the Fetch api to retrieve data from an api. For example, I will use a fictitious api containing employee information. I’ll demonstrate how to get data using the Fetch () api method.
The Fetch () method in JavaScript is modern and versatile, and modern browsers widely support it. It can send network requests to the server and load new information without reloading the browser.
The Fetch () method takes only one mandatory argument, which is the URL of the resource to be retrieved.
([response = fetch(api url, [other parameters])
Awaiting JavaScript Async: In this example, we will use the Async Await method in conjunction with the To make promises more concisely, use the Fetch () method. All modern browsers support async functions.
Prerequisites
You will need the following items to complete this tutorial:
- A Node js local development environment. Follow How to Install Node.js and Create a Local Development Environment.
- You have a fundamental understanding of JavaScript coding, which you can learn more about by visiting the How to In the JavaScript series and writing code.
- An understanding of JavaScript Promises. Read the Promises section of this article on JavaScript’s event loop, callbacks, Promises, and async/await.
Step 1: Understanding Fetch api syntax
One method for using the Fetch api is to pass the URL of the api as a parameter to
fetch(url)
A Promise is return by the fetch() method. Include the Promise method then() after the fetch() method:
fetch(url) .then(function(){ // handle the response })
If the Promise returned is resolved, the then() method’s function is executed. This function contains the code for dealing with the api data.
Include the catch() method after the then() method:
fetch(url)
.then(function() {
// handle the response
})
.catch(function() { // handle the error
});
The api you call with Fetch () may be unavailable, or other errors may occur. So, if this occurs, the reject promise is return. To handle rejection, the catch method is use. If an error occurs while calling the api of your choice, the code within the catch() will be execute.
You can now use Fetch () on a real api after you’ve mastered the syntax for using the Fetch api.
Step 2 — Obtaining Data from an api using Fetch
The JSONPlaceholder api will be use in the following code samples. So, you will get ten users from the api and use JavaScript to show them on the page. This tutorial will pull information from the JSONPlaceholder api and show it in the form of list items within the framework of the author’s list.
Begin by creating an HTML file and inserting a heading and an unordered list with the authors’ ids:
Authors.html
<h1>Authors</h1>
<u1 id=”authors”></u1>
And show them on the document using JavaScript. This tutorial pulls data from the JSONPlaceholder api and displays it.
Authors.html
<h1>Authors</h1> <u1 id=”authors”></u1>
<script> conset u1 = document.getElement Byld ( ‘authors’ ); </script>
Remember that the author is the id for the previously create ul.
Create a list that is a Document Fragment next:
Authors.html
<script>
// ...
const list = document.createDocumentFragment();
</script>
All attached list items will be included in the list. Then the active document tree structure does not include a DocumentFragment. When the Document Object Model is changed, this prevents performance-impacting redraws.
Create a constant variable called url that will hold the JavaScript Fetch API URL for returning ten random users:
Authors.html
<script>
// ...
const url = 'https://jsonplaceholder.typicode.com/users';
</script>
Now, using Fetch api, use Fetch () with the reasoning url to call the JSONPlaceholder api:
Authors.html
<script> // … fetch(url) </script>
You’re using the JavaScript Fetch API. You could use the cleaner syntax to get the URL for the JSONPlaceholder API. Then there is a response. However, the response is an object with a series of methods that can be used depending on what you want to do with the information rather than JSON. Use the JSON () method to convert the returned object to JSON.
Add the then() method, which will contain a function with a response parameter:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {})
</script>
The cost of the component is the object return from fetch (url). To convert the answer into JSON data, use the JSON() process:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
</script>
The JSON data must still be process. Add another then() statement with a function with a data argument:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {})
</script>
Create a variable called authors within this function and set it to data:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
})
</script>
Then Create a list item that displays the author’s name for each author in authors. However this pattern is well-suited to the map() method:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
});
})
</script>
Within your map function, because create a thing called li that will be set equal to createElement with li (the HTML element) as the argument. Then create an h2 for the name and a span for the email:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
});
})
</script>
The author’s name will appear in the h2 element. The author’s email address will be display in the span element. Then this is possible thanks to the inner HTML property and string interpolation:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = ${author.name}`; email.innerHTML = ${author. Email}`;
});
})
</script>
Next, use appendChild to relate these DOM elements:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = `${author.name}`;
email.innerHTML = `${author.email}`;
li.appendChild(name);
li.appendChild(email);
list.appendChild(li);
});
})
ul.appendChild(list);
</script>
It should be noted that each list item is append to the DocumentFragment list. Once the map is finish, the list is appended to the ul unordered list element.
Because after you’ve finished both the () functions, you can add the catch() function. This function will print the following error message to the console:
Authors.html
<script>
// ...
fetch(url)
.then((response) => {
// ...
})
.then((data) => {
// ...
})
.catch(function(error) {
console.log(error);
});
// ...
</script>
This is the complete code for the request you create:
Authors.html
<h1>Authors</h1>
<ul id="authors"></ul>
<script>
const ul = document.getElementById('authors');
const list = document.createDocumentFragment();
const url = 'https://jsonplaceholder.typicode.com/users';
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
let authors = data;
authors.map(function(author) {
let li = document.createElement('li');
let name = document.createElement('h2');
let email = document.createElement('span');
name.innerHTML = `${author.name}`;
email.innerHTML = `${author.email}`;
li.appendChild(name);
li.appendChild(email);
list.appendChild(li);
});
}).
.catch(function(error) {
console.log(error);
});
ul.appendChild(list);
</script>
Then you just completed a GET request with the JSONPlaceholder api and the Fetch api.
Conclusion
While not all browsers support the Fetch api, it is a great alternative to XMLHttpRequest. So, if you like to know how to utilize React to call Web apis, you should read this article.
tadalafil drug brand tadalafil 20mg buy ed pills generic
buy tadalafil 20mg for sale cialis 20mg pill where to buy ed pills without a prescription
isotretinoin 20mg oral purchase zithromax generic buy azithromycin 250mg sale
generic accutane 40mg accutane 10mg cost buy zithromax 250mg for sale
order azipro without prescription prednisolone 10mg uk buy neurontin
furosemide 40mg price order doxycycline 200mg generic purchase ventolin for sale
lasix us lasix price buy generic ventolin inhalator
buy altace sale order arcoxia for sale arcoxia 60mg usa
order vardenafil 20mg for sale purchase tizanidine without prescription hydroxychloroquine 400mg pill
buy vardenafil tablets tizanidine pills order hydroxychloroquine 400mg online cheap
buy altace 10mg pills buy etoricoxib order arcoxia online cheap
order vardenafil 20mg generic order vardenafil for sale hydroxychloroquine 400mg generic
buy mesalamine 800mg online order generic mesalamine 400mg buy generic irbesartan over the counter
order vardenafil 20mg sale order plaquenil 200mg generic hydroxychloroquine 400mg without prescription
buy asacol 800mg for sale buy asacol generic oral irbesartan
olmesartan 10mg canada order benicar sale depakote 250mg cheap
buy benicar sale calan where to buy buy depakote 500mg pill
buy temovate generic cordarone oral buy cordarone 100mg without prescription
clobetasol without prescription buspirone 10mg price buy cordarone without a prescription
buy acetazolamide 250mg pill imuran 25mg canada imuran ca
buy acetazolamide medication buy diamox 250 mg pills imuran price
digoxin online telmisartan 80mg cost molnunat oral
lanoxin 250 mg without prescription buy micardis tablets buy generic molnupiravir over the counter
Way cool! Some very valid points! I appreciate you writing this post and the rest
of the site is very good.
Feel free to surf to my site free mp3 download
order naprosyn 250mg online cheap naprosyn 500mg cost where can i buy prevacid
buy naprosyn 500mg pill buy omnicef online purchase prevacid online
order coreg 25mg pill coreg uk aralen 250mg us
buy coreg no prescription order coreg buy chloroquine 250mg sale
proventil 100mcg generic purchase pantoprazole pill phenazopyridine online order
order albuterol pantoprazole 40mg drug pyridium 200 mg tablet