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
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
Similar Reads
Fetch API in JavaScript The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.Syntaxfetc
6 min read
Fetch API in JavaScript The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests. It replaces the older XMLHttpRequest method and provides a cleaner and more flexible way to fetch resources asynchronously. The Fetch API uses Promises, making it easier to work with asynchronous data.Syntaxfetc
6 min read
Git Fetch Before git fetch, developers had to manually check or pull all changes from a remote repository. The problem was that git pull would automatically merge changes, which could lead to unwanted updates or merge conflicts if you were not ready. To solve this, Git introduced git fetch.It simply checks fo
4 min read
Next.js Data Fetching Next.js Data Fetching refers to the process of getting data from a server or an API and displaying it on a webpage. Next.js offers multiple data-fetching methods to handle server-side rendering, static generation, and client-side rendering. These methods enable you to fetch and manage data efficient
6 min read
Git Fetch All Branches In Git, keeping track of all branches in a remote repository is important. The git fetch command is a powerful tool for retrieving updates from a remote repository. While itâs common to fetch changes from a single branch, there are some cases when you need to fetch updates from all branches, especia
4 min read
Get and Post method using Fetch API The fetch() method is used to send HTTP requests to the server without refreshing the page, providing an efficient alternative to the older XMLHttpRequest object. One of the main advantages of fetch() is that it uses Promises, which allow for better management of asynchronous operations compared to
4 min read