Exploring Fetch API - SkillBakery Studios


Post Top Ad

Post Top Ad

Saturday, October 10, 2020

Exploring Fetch API

 The Fetch API is a simple interface for fetching resources. Fetch makes it easier to make web requests and handle responses than with the older XMLHttpRequest, which often requires additional logic (for example, for handling redirects). In other words Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.

The fetch specification differs from jQuery.ajax() in three main ways:


·       The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

·        fetch() can receive cross-site cookies; you can establish a cross-site session using fetch. 

·        fetch won’t send cookies unless you set the credentials init option.


Using Fetch

The function fetch is available in the global window scope, fetch is making an HTTP request to get the file.jsonresource on the same domain.



 The contents are-


  .then(response => response.json())

  .then(data => console.log(data))


Calling fetch() returns a promise, then the promise is resolved by passing a handler with the then()  method of the promise, then the handler receives the return value of the fetch promise, a Response object.


 Catching errors

Fetch() returns a promise, we can use the catch method of the promise to intercept any error occurring during the execution of the request, and the processing done in the then call backs



.then(response => {



.catch(err => console.error(err))

 There is one more way of catching errors, is to manage them in the first then


.then(response => {

  if (!response.ok) { throw Error(response.statusText) }

  return response


.then(response => {




Response Object

The Response Object returned by a fetch() call contains all the information about the request and the response of the network request.



Accessing the headers property on the response object gives you the ability to look into the HTTP headers returned by the request:


fetch('./file.json').then(response => {





This property is an integer number representing the HTTP response status.

·        101, 204, 205, or 304 is a null body status

·        200 to 299, inclusive, is an OK status (success)

·        301, 302, 303, 307, or 308 is a redirect


·        fetch('./file.json').then(response => console.log(response.status))



statusText is a property representing the status message of the response. If the request is successful, the status is OK.

fetch('./file.json').then(response => console.log(response.statusText))



url represents the full URL of the property that we fetched.

fetch('./file.json').then(response => console.log(response.url))

Body content

A response has a body, accessible using several methods:

·        text() returns the body as a string

·        json() returns the body as a JSON-parsed object

·        blob() returns the body as a Blob object

·        formData() returns the body as a FormData object

·        arrayBuffer() returns the body as an ArrayBuffer object

All those methods return a promise. Examples:


  .then(response => response.text())

  .then(body => console.log(body))


  .then(response => response.json())

  .then(body => console.log(body))

Request Object

The Request object represents a resource request, and it’s usually created using the new Request() API.


const req = new Request('/api/todos')

The Request object offers several read-only properties to inspect the resource request details, including

·        method: the request’s method (GET, POST, etc.)

·        URL: the URL of the request.

·        headers: the associated Headers object of the request

·        referrer: the referrer of the request

·        cache: the cache mode of the request (e.g., default, reload, no-cache).

And exposes several methods including json()text() and formData() to process the body of the request.


Request headers

Being able to set the HTTP request the header is essential, and fetch gives us the ability to do this using the Headers object:

const headers = new Headers()

headers.append('Content-Type', 'application/json')


const headers = new Headers({

  'Content-Type': 'application/json'


To attach the headers to the request, we use the Request object, and pass it to fetch()instead of passing the URL.

Instead of:


we do

const request = new Request('./file.json', {

  headers: new Headers({

    'Content-Type': 'application/json'




The Headers object is not limited to setting value, but we can also query it:



and we can delete a header that was previously set:



POST Requests

Fetch also allows to use of any other HTTP method in your request: POST, PUT, DELETE or OPTIONS.

Specify the method in the method property of the request, and pass additional parameters in the header and in the request body:

Example of a POST request:

const options = {

  method: 'post',

  headers: {

    'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'


  body: 'name=Flavio&test=1'



fetch(url, options).catch(err => {

  console.error('Request failed', err)


Cancel a fetch request

A generic API to notify abort events AbortController and AbortSignal, integrate this API by passing a signal as a fetch parameter:

const controller = new AbortController()

const signal = controller.signal


fetch('./file.json', { signal })

A timeout can be set, through an abort event, 5 seconds after the fetch request has started, and the same will be canceled.


setTimeout(() => controller.abort(), 5 * 1000)

If the fetch returns the object before timeout,

For all the latest and fresh courses please do visit our website


No comments:

Post a Comment

Post Top Ad