You do not need jQuery of three new AJAX methods fetch of

  • 2021-06-28 10:41:34
  • OfStack

XMLHttpRequest to complete ajax is a bit old-fashioned.

fetch() enables us to perform ajax functions similar to those provided by XMLHttpRequest (XHR).The main difference between them is that Fetch API uses Promises, which makes the interface simpler and simpler, avoids the complexity of callbacks and eliminates the use of complex XMLHttpRequest API.

If you haven't used Promises before, you should first read the article JavaScript Promises Usage.

1. Basic Fetch usage

Let's start with an example to compare the differences between using XMLHttpRequest and using fetch under 1.We want to request an URL to get the return in JSON format.

XMLHttpRequest
An XMLHttpRequest request requires two listeners to capture both success and error scenarios and calls to the open () and send () methods.


function reqListener() { 
 var data = JSON.parse(this.responseText); 
 console.log(data); 
}

function reqError(err) { 
 console.log('Fetch Error :-S', err); 
}

var oReq = new XMLHttpRequest(); 
oReq.onload = reqListener; 
oReq.onerror = reqError; 
oReq.open('get', './api/some.json', true); 
oReq.send();

Fetch
The code for our fetch request is basically the following:


fetch('./api/some.json') 
 .then( 
 function(response) { 
  if (response.status !== 200) { 
  console.log('Looks like there was a problem. Status Code: ' + 
   response.status); 
  return; 
  }

  // Examine the text in the response 
  response.json().then(function(data) { 
  console.log(data); 
  }); 
 } 
 ) 
 .catch(function(err) { 
 console.log('Fetch Error :-S', err); 
 });

We first check whether the status of the request response is 200, then analyze the response data according to the JSON object.

The content requested by fetch () is an Stream object.That is, when we call the json() method, an Promise object is returned, because the read to stream is also asynchronous.

Return metadata for data objects (Metadata)

In the example above, I see the basic state of the server response object Response and how to convert it to JSON.There is still a lot of metadata information in the corresponding object Response returned, here are some:


fetch('users.json').then(function(response) { 
 console.log(response.headers.get('Content-Type')); 
 console.log(response.headers.get('Date'));

 console.log(response.status); 
 console.log(response.statusText); 
 console.log(response.type); 
 console.log(response.url); 
});

Response object Response type

When we execute an fetch request, the type of data we respond to, response.type, can be "basic", "cors" or "opaque".These types are used to illustrate how these data and data sources should be treated.

When a request originates from the same domain, the type of response will be "basic", and there will be no restrictions on the use of the response content.

If the request comes from another domain and the response has CORs header information, the type of response will be "cors".Responses of types cors and basic are basically the same, except that responses of type cors restrict the amount of header information you can see only `Cache-Control', `Content-Language', `Content-Type', `Expires', `Last-Modified', and `Pragma

The response of type "opaque" indicates that the request came from another domain and did not have CORS header information.A response of type opaque will not be read, and the status of the request will not be read, and the success of the request will not be seen.The current fetch () implementation cannot execute such a request.

You can specify a mode for an fetch request and require that it only execute requests in the specified mode.This pattern can be divided into:

"same-origin" only requests from the same domain will succeed and all others will be rejected.
"cors" allows requests from different domains, but requires correct CORs header information.
"cors-with-forced-preflight" executes preflight check before making a real call.
"no-cors" is currently an impossible mode to execute.
The pattern is defined by using a parameter object as the second parameter of the fetch method:


fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}) 
 .then(function(response) { 
 return response.text(); 
 }) 
 .then(function(text) { 
 console.log('Request successful', text); 
 }) 
 .catch(function(error) { 
 log('Request failed', error) 
 });

Serial Promises

One of the biggest features of Promises is that you can concatenate operations.For fetch, we can share a few logical operations in each fetch operation.

When using JSON API, we need to check the status of each request response and resolve it to an JSON object.With promise, we can simply put the analysis state and code that parses JSON into a separate function and return it as promise, which makes the code more organized.


function status(response) { 
 if (response.status >= 200 && response.status < 300) { 
 return Promise.resolve(response) 
 } else { 
 return Promise.reject(new Error(response.statusText)) 
 } 
}

function json(response) { 
 return response.json() 
}

fetch('users.json') 
 .then(status) 
 .then(json) 
 .then(function(data) { 
 console.log('Request succeeded with JSON response', data); 
 }).catch(function(error) { 
 console.log('Request failed', error); 
 });

We use the status function to examine response.status and return the result of Promise.resolve() or Promise.reject(), which is also an Promise.In our chain of fetch () calls, first if fetch () executes as resolve, then the json () method is called, which also returns an Promise, so we get an JSON object after analysis.If the analysis fails, the reject function and the catch statement are executed.

You will find that in the fetch request, we can share some business logic to make the code easier to maintain, more readable, and more testable.

Perform form data submission with fetch

Submitting a form is a very common operation in WEB applications, and it is very simple to submit form data using fetch.

method and body parameter options are provided in fetch.


fetch(url, { 
 method: 'post', 
 headers: { 
  "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
 }, 
 body: 'foo=bar&lorem=ipsum' 
 })
 .then(json) 
 .then(function (data) { 
 console.log('Request succeeded with JSON response', data); 
 }) 
 .catch(function (error) { 
 console.log('Request failed', error); 
 });

Send user identity credential information in Fetch request

If you want to include credential information such as cookies in the fetch request, you can set the credentials parameter to the value "include".


fetch(url, { 
 credentials: 'include' 
})

It is clear that fetch API is much simpler than the traditional XMLHttpRequest (XHR), and no less so than the ajax API offered in jQuery.


Related articles: