JavaScript Fetch API

Ashiq
Updated 30 May 2021
HIGHLIGHTS
  • All about javascript fetch API
  • How to use fetch()

It was always a nightmare to use XMLHttpRequest in javascript to make api calls without page refresh. Although I mostly prefered jQuery.ajax() because of its simplicity.

With the rise in web application and demand for asynchronous data loading we got to see XMLHttpRequest, jQuery.ajax(), and now fetch().

😀 No need for XMLHttpRequest anymore.

It 2021 and applications are highly dependant on asynchronous data loading may be for loading search suggestion, load more comments on a tread, load content on scroll etc. Thus we javascript developers are blessed to have updated version of XMLHttpRequest i.e js fetch().

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
Source : developer.mozilla.org

The Fetch API interface allows web browser to make HTTP requests to web servers. The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request. Along with path you can also pass various options (urlencoded, formdata etc), headers.

A fetch request is really simple to use, here's an example:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data));


To send otional parameters, have a look at the below code


let data = {
	title : "This is title"
	post : "This is post"
}
let options = {
	method: 'POST',
	mode: 'cors',
	cache: 'no-cache',
	credentials: 'same-origin',
	headers: {
	  'Content-Type': 'application/json'
	},
	body: JSON.stringify(data)
}
fetch('https://domain.com/post',options)
  .then(response => response.json())
  .then(data => console.log(data));


A normal fetch request wont send cross-origin cookies unless you set the credentials init option

fetch('https://domain.com/wallet',{
  credentials: 'include'
})
  .then(response => response.json())
  .then(data => posted(data));

function posted(r){
	console.log(r);
}


Well, how about catching error

fetch('https://domain.com/fetch')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (err) {
        console.log("Oops something went wrong!", err);
    });


Browser Support

The Fetch API is supported by majority of browsers, except Internet Explorer and Opera mini. People using releases of Chrome, Firefox and Safari older than 2017 may also experience problems. Those users may forms a tiny proportion of today's internet.

Can I get file upload progress with fetch?

At the time of writing, Fetch has no support for progress events. It is therefore impossible to report the status of file uploads or similar large form submissions.

Fallback

You could opt for a Fetch polyfill in conjunction with a Promise polyfill so it’s possible to write Fetch code in IE. However, XHR is used as the fallback; not every option will work as expected, e.g. cookies will be sent regardless of settings.

Fetch is the future. However, the API is relatively new, it does not provide all XHR functionality, and some options are cumbersome.