JavaScript fetch API usages, request options, async-await, intercepting, cancel request, and promise all

Fetch API is not experimental anymore, It is Living Standard as per MDN. We have to cover in this article Fetch API use-cases and different aspects of usages. Fetch provides a generic definition of request and response object and it will involve in network requests.

The function fetch() is part of the global window object. It is a modern replacement for XMLHttpRequest. This can be used in code almost any part of the context.

Fetch

The fetch() has required one mandatory argument that is the URL of the resource. It returns a promise that resolves the response.

// GET Request.
fetch('https://api.github.com/users/rich-harris')
  // Handle success
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); // Catch errors

Request Options

The request also has an optional second argument with different request options. if you send JSON as the body it requires to use JSON.stringify()

/**
 * Fetch API
 * The option with * is the default
 */
{
  method: "POST", // *GET, POST, PUT, DELETE, etc.
  mode: "cors", // no-cors, cors, *same-origin
  cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
  credentials: "same-origin", // include, *same-origin, omit
  headers: {
    "Content-Type": "application/json", 
    // "Content-Type": "application/x-www-form-urlencoded",
  },
  redirect: "follow", // manual, *follow, error
  referrer: "no-referrer", // no-referrer, *client,
  body: JSON.stringify(data)
}

Sample POST request with request options

fetch('/save/data', {
  method: 'POST',  
  body: JSON.stringify(data),// if sending data as array or object
  headers: {
    'Content-Type': 'application/json'
  }
})

If HTML form as data the body will be

body: new FormData(form), // post body as form data
headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
}

#javascript #web-development #programming #api #developer

The Ultimate JavaScript Fetch API Cheatsheet
2.05 GEEK