Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Fetch API

JS Web Fetch API

The Fetch API interface allows web browser to make HTTP requests to web servers.

What is a Fetch API?

The Fetch is promise-based API that provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses to fetch resources asynchronously across the network.

A Fetch API Example

A basic fetch request looks like this:

					 
        
          async function logMovies() {
            const response = await fetch("http://example.com/movies.json");
            const movies = await response.json();
            console.log(movies);
          }
        
      
Supplying Request Options

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:

					 
        
          async function postData(url = "", data = {}) {
            // Default options are marked with *
            const response = await fetch(url, {
              method: "POST", // *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/json",
                // 'Content-Type': 'application/x-www-form-urlencoded',
              },
              redirect: "follow", // manual, *follow, error
              referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, 
              // origin, origin-when-cross-origin, same-origin,
              // strict-origin, strict-origin-when-cross-origin, unsafe-url
              body: JSON.stringify(data), // body data type must match "Content-Type" header
            });
            return response.json(); // parses JSON response into native JavaScript objects
          }

          postData("https://example.com/answer", { answer: 42 }).then((data) => {
            console.log(data); // JSON data parsed by `data.json()` call
          });
        
      
Aborting a fetch

To abort incomplete fetch() operations, use the AbortController and AbortSignal interfaces.

The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.

The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object.

					 
        
          const controller = new AbortController();
          const signal = controller.signal;
          const url = "video.mp4";

          const downloadBtn = document.querySelector("#download");
          const abortBtn = document.querySelector("#abort");

          downloadBtn.addEventListener("click", async () => {
            try {
              const response = await fetch(url, { signal });
              console.log("Download complete", response);
            } catch (error) {
              console.error(`Download error: ${error.message}`);
            }
          });

          abortBtn.addEventListener("click", () => {
            controller.abort();
            console.log("Download aborted");
          });
        
      
Uploading a file

Files can be uploaded using an HTML <input type="file" /> input element, FormData() and fetch().

					 
        
          async function upload(formData) {
            try {
              const response = await fetch("https://example.com/profile/avatar", {
                method: "PUT",
                body: formData,
              });
              const result = await response.json();
              console.log("Success:", result);
            } catch (error) {
              console.error("Error:", error);
            }
          }

          const formData = new FormData();
          const fileField = document.querySelector('input[type="file"]');

          formData.append("username", "abc123");
          formData.append("avatar", fileField.files[0]);

          upload(formData);
        
      

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved