DEV Community

Cover image for Fetch API in JavaScript
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

Fetch API in JavaScript

Hi 👋
Fetching data from a website, or even a local inside your code can be a real headache sometimes. There are many methods that we generally use to get and use data from external sources or files inside our projects. We can even get Our Data from Google Sheets if we use the correct methods. Here we are going to discuss about the Fetch API today.

About Fetch API

The Fetch API is an interface that allows you to make HTTP requests to the server from web browsers.

  • If you have worked with XMLHttpRequest (XHR) object.
  • Fetch API can perform all the tasks as the XHR object does.
  • Fetch API is much simpler and cleaner.
  • It uses the promise to deliver more flexible features to make requests to servers from the web browser.

Sending a Request

The fetch() method is available in the global scope that instructs the web browsers to send a request to a URL.

  • The fetch() requires only one parameter, the URL of the resource that you want to fetch.
  • When the request completes, the promise resolves into a Response object.
let response_obj_var = fetch(URL);
Enter fullscreen mode Exit fullscreen mode

Reading the response

The fetch() method returns a promise so you can use the then() and catch() methods to handle it

fetch(URL)
     .then((response) => {
          //handle the response
          console.log(response)
     })
     .catch((error) => {
          //handle the error
          console.warn(error)
     });
Enter fullscreen mode Exit fullscreen mode

Handling Data

If the contents of the response are in the raw format, you use the text() method.
The text() method returns a Promise that resolves with the complete contents of the fetched resource.

fetch('/readme.txt')
     .then(response => response.text())
     .then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Besides the text() method, the response object has different other methods, such as json(), blob(), formData(), arrayBuffer() and many more, to handle the respective type of data. In practice, you often use async/await with the fetch() method like this:

async function fetchDataFunc() {
     let response = await fetch('/readme.txt');
     let data = await response.txt();
     console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

Handling the status codes

The response object provides the status code and status text via the status and statusText properties.

async function fetchDataFunc() {
     let response = await fetch('/readme.txt');

     console.log(response.status); // returns 200
     console.log(statusText); // returns OK

     if (response.status === 200) {
          let data = await response.text()
          // handle data
     }
}

fetchDataFunc();
Enter fullscreen mode Exit fullscreen mode

I hope you would have liked this article. Do comment below or mail me at mursalfurqan@gmail.com to let me know what you want to read next week.

Till then, have an amazing weekend and Happy Coding 🎉.

Top comments (1)

Collapse
 
artydev profile image
artydev

Thank you