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.
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, 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
.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 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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Oct, 2021
Like Article
Save Article