Eazy Way to, How to Fetch API using JavaScript..🎇

roshan_100kar

Roshan Shambharkar

Posted on May 21, 2022

Eazy Way to, How to Fetch API using JavaScript..🎇

So How Do we Fetch API in JavaScript in, javaScript There is a inbuild method which is called fetch()The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that returns the data of the format JSONor XML. This method returns a promise,

Image description
So lets come up with the Approach,
Step 1. First make the necessary JavaScript file, HTML file and CSS file.
Step 2. Then store your API URL in a variable.
Step 3. Define a async function (here getapi()) and pass api_url in that function.
Step 4. Define a constant response and store the fetched data by await fetch() method
So lets get start

First We will Create HTML file And Js files
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript</title>
</head>
<body>
<main id="app"></main>
</body>
</html>

JAVAScript File

`function getData() {
fetch("https://reqres.in/api/users")
.then(res => {
return res.json();
})
.then(json => {
console.log(json.data);
const html = json.data
.map(function(item) {
return "

" + item.first_name + " " + item.last_name + "

";
})
.join("");
console.log(html);
document.querySelector("#app").insertAdjacentHTML("afterbegin", html);
})
.catch(error => {
console.log(error);
});
}

getData();`

You can find output of this Example in here

💖 💪 🙅 🚩
roshan_100kar
Roshan Shambharkar

Posted on May 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related