JavaScript Fetch API

JavaScript Fetch API

The fetch method in javascript requests the server and then loads information on the webpage.

·

2 min read

Summary

In this article, you will learn about JavaScript Fetch API and how to fetch the resource across the network. JavaScript Fetch API is similar to the XmlHttpRequest (XHR) object and performs similar tasks as XMR object. So now there is no need for XHR. Further, we will discuss how to fetch URL and how to use promises to access data using fetch API.

Concept of fetch()

Ever think about how our website interacts with the server, and how requests and responses take place?

Fetch is behind this functionality this method in javascript requests the server and then loads it on the webpage. The transfer data is in JSON format which is lightweight and easy to transfer between networks. It then returns a promise which resolves into a response object.

Accessing data

First, we will create a JSON format data file and then we will access data from that file using Fetch API

Creating JSON file countries.json

Know about JSON

[{
  "country": "India",
  "language":"Hindi"
},
{
  "country": "USA",
  "language":"English"
},
{
  "country": "France",
  "language":"French"
}]

Fetching data from file from JSON to normal object form

const url = 'countries.json' // countries json file
fetch(url)
  .then(response => response.json()) // accessing the API data as JSON
  .then(data => {
    // accessing the data
    console.log(data)
  })
  .catch(error => console.error(error)) // handling error if something wrong happens

Note: fetch doesn't transfer any cookies from the server

fetch(): fetch is a method that is getting data from the server.

.then: It is a fetch method that handles the data from the server.

.catch: It handles the error if occurs.

There are some more methods of fetch described below.

json(): to resolve promises with JSON format data

clone(): for creating clones of response

redirect(): to create some response with a different URL

Conclusion

I gave some basic ideas about the fetch method of JavaScript. How does it work and what are its methods? How to handle responses from the server? How to deal with JSON files? And many more.

Hope you enjoyed the article.

Please comment and upvote if you liked it.