Fetch API - GeeksforGeeks

27 Oct, 2021
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:  
clone(): for creating a clone of response.redirect(): for creating strong response with different url.arrayBuffer(): we return a Promise that resolves with an ArrayBuffer.formData(): also returns a Promise that resolves with a FormDataObject.blob(): same as above only that resolves with a blob.text(): this resolves with a string.json(): it resolves promise with JSON.
clone(): for creating a clone of response.
redirect(): for creating strong response with different url.
arrayBuffer(): we return a Promise that resolves with an ArrayBuffer.
formData(): also returns a Promise that resolves with a FormDataObject.
blob(): same as above only that resolves with a blob.
text(): this resolves with a string.
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:  
method: GET, POST, PUTurl: URL of the requestheaders: Headers objectreferrer: referrer of the requestmode: cors, no-cors, same-origincredentials: should cookies go with the request? omit, same-origincache: cache mode (default, reload, no-cache)
method: GET, POST, PUT
url: URL of the request
headers: Headers object
referrer: referrer of the request
mode: cors, no-cors, same-origin
credentials: should cookies go with the request? omit, same-origin
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:  
javascript
fetch('https://www.reddit.com/r/javascript/top/.json?limit=5').then(res=>res.json()).then(json=>console.log(json));
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:  
javascript
async function demo(subject){   const URL='https://www.reddit.com/r/javascript/top/.json?limit=5';   const Res= fetch(URL);   const response= await Res;   const json= await response.json();   console.log(json);}demo('javascript');
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 
rajeev0719singh
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
Node.js fs.readFileSync() Method
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?