Fetch API

 · 4 mins read

Fetch API

In fact, I have never used Fetch API before, just old traditional AJAX in practical work. Maybe it’s because many libraries like jQuery have well encapulated the XHR(XMLHttpRequest) so that we don’t worry about the compatiblity of various kinds of browsers. Today I learnt the Fetch API through MDN, and wrote them down in order to strengthen my memory.

Will Fetch replace XHR in the future?

I don’t know, honestly. But since the Fetch API is the newer thing, which seems more cooler, it should be better than XHR, thus we should keep up with this new technogoly.

Here we go!


The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but it provides a more powerful and flexible feature set. This article explains some of the basic concepts of the Fetch API.

In a nut shell

At the heart of Fetch are the Interface abstractions of HTTP Requests, Responses, Headers, and Body payloads, along with a global fetch method for initiating asynchronous resource requests. Because the main components of HTTP are abstracted as JavaScript objects, it is easy for other APIs to make use of such functionality.

Service Workers(which I would study later) is an example of an API that makes heavy use of Fetch.

Fetch takes the asynchronous nature of such requests one step further. The API is completely Promise-based.

differences between Fetch and jQuery.ajax

Note that the fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

  • 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.
  • By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

Usage:

jsut two steps:

  1. fetch(path, options)

  2. add .then() or .catch()

Use fetch() to POST JSON-encoded data.

var url = 'https://example.com/profile';
var data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), 
  headers: new Headers({
    'Content-Type': 'application/json'
  })
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

The most exciting thing is Fetch API use Promise, so your code could look more clearer than it used to be. What is more,you can freely set your header and other parameters to any form you want, and have response at your proposal.

Before you really dive into it, you should know these objects:

  • Request
  • Headers
  • Response
fetch(path, options)  
// =
var request = new Request(path, options)
fetch(request)  

The most common response properties you’ll use are:

– Response.status — An integer (default value 200) containing the response status code.

– Response.statusText — A string (default value “OK”),which corresponds to the HTTP status code message.

– Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean.

Checking that the fetch was successful:

fetch('flowers.jpg').then(function(response) {
  if(response.ok) {
    return response.blob();
  }
  throw new Error('Network response was not ok.');
}).then(function(myBlob) { 
  var objectURL = URL.createObjectURL(myBlob); 
  myImage.src = objectURL; 
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ', error.message);
});

The Body mixin defines the following methods to extract a body (implemented by both Request and Response). These all return a promise that is eventually resolved with the actual content.

  • arrayBuffer()
  • blob()
  • json()
  • text()
  • formData()

There are many cases I don’t want to list them all, click links if you are interested.


Disadvantages:

Fetch API can’t cancel a operation, because it return a Promise, while Promise can’t abort!

What I feel

Fetch API is very powerful, but it still needs to address some issues(like abort), and I think it’s not easy for beginners to pick up, as they must learn Promise, and what’s more complicated, dazzling configurations. One must grasp the common http request and reponse before it become your Victorinox-Swiss Army Knife.


LINKS:

fetch-blog

Fetch API-MDN