Fetch API

For long XMLHttpRequest is being used by web developer’s trusted “amigo”. XMLHttpRequest has enabled ajax and a whole new kind of interactive exposure.
However, it is being slowly succeeded by the Fetch API. These both deliver the same work i.e. fetching data asynchronously from a different network, but the Fetch API is Promise based. This provides a more cleaner and more concise syntax.

The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve response of the request.

Basic Syntax:



 fetch(url) //call the fetch function passing the url of the API as a parameter
.then(function(){
  //code for handling data from API
});
.catch(function(){
  //code when the server returns any error
});

NOTE: By default, fetch() will not send or receive any cookies from the server, resulting in unauthenticated requests.

Below are list of methods which can be used when we get a response on what we want to do with the information:

  1. clone(): for creating a clone of response.
  2. redirect(): for creating strong response with different url.
  3. arrayBuffer(): we return a Promise that resolves with an ArrayBuffer.
  4. formData(): also returns a Promise that resolves with a FormDataObject.
  5. blob(): same as above only that resolves with a blob.
  6. text(): this resolves with a string.
  7. json(): it resolves promise with JSON.

Request:
A Request object represents the request part of a fetch call. By passing fetch a Request you can make advanced and customized requests:

  1. method: GET, POST, PUT
  2. url: URL of the request
  3. headers: Headers object
  4. referrer: referrer of the request
  5. mode: cors, no-cors, same-origin
  6. credentials: should cookies go with the request? omit, same-origin
  7. cache: cache mode (default, reload, no-cache)

LOADING JSON
We cannot block the user interface waiting until the request completes. That is why fetch() method returns a Promise. A promise is actually an object which represents a future result. The then() method is used to wait for the response from the server-side and log it to the console.

Below code snippet explains the above logic:

filter_none

edit
close

play_arrow

link
brightness_4
code

.then(res=>res.json())
.then(json=>console.log(json));

chevron_right


Async…await
This provides a more concise way to process Promises. Its functionality is that we can mark a function as async, then wait for the promise to finish with the await, and access the result as a normal object.

Simple example demonstrating how async…await can be used:

filter_none

edit
close

play_arrow

link
brightness_4
code

async function demo(subject){
   const Res= fecth(URL);
   const response= await Res;
   const json= await response.json();
   console.log(json);
}
demo('javascript');

chevron_right


HANDLING ERRORS:
What if we ask the server for a non-existing resource that requires permissions/authorization? With fetch(), we can handle application-level errors like 404 responses.

Although Fetch API is superseding XMLHttpRequest still a beginner needs to learn XMLHttpRequest to make more effective use of Fetch API.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.