How does fetch request data

  css, Front end, html, javascript, Programmer

A preface

In the traditional Ajax era, network requests such as API are made through XMLHttpRequest or the encapsulated framework. However, the configuration and calling methods are very chaotic and are not friendly to beginners. Fetch, which we introduced today, provides a better alternative. It not only provides a simple and logical way to obtain resources asynchronously across the network, but also can be easily used by other technologies, such as Service Workers.
The starting address of this article isGitHub blog, writing articles is not easy, please support and pay more attention!


Second, compared with Ajax

Using Ajax to request a JSON data usually looks like this:

var xhr = new XMLHttpRequest();'GET', url/file,true);
 xhr.onreadystatechange = function() {
 var data=xhr.responseText;
 xhr.onerror = function() {
 console.log("Oh, error");

Similarly, we use fetch to request JSON data:

Fetch (URL). then (response = > response. JSON ())//resolves to readable data
 . then (data = > console.log (data))//call the then method when the execution result is resolve
 . catch (err = > console.log ("oh, error, err))//call the catch method when the execution result is reject

From the comparison between the two, fetch code is much simpler and the business logic is clearer, making the code easier to maintain and more readable.
To sum up, Fetch has the following advantages:

1. The grammar is concise, more semantic and the business logic is clearer

2. Based on the standard Promise implementation, supports async/await

3. Isomorphism is convenient and easy to useisomorphic-fetch

Brief Introduction of Three Promise

Since Fetch API is based on Promise design, we will briefly introduce the workflow of Promise next so that everyone can better understand Fetch.

The fetch method returns a Promise object. According to the characteristics of the Promise Api, fetch can easily use the then method to string all processing logics together. Using the Promise.resolve () or Promise.reject () methods will return the Promise with positive or negative results respectively, thus calling the next then or catch. If there is an error in the statement in then, it will also jump to catch.

4. Common data formats for requests

Next, we will introduce how to use fetch to request local text data, request local JSON data, and request network interfaces. In fact, the operation is much simpler than Ajax!

//HTML section
 <div class="container">
 <h1>Fetch Api sandbox</h1>
 < button id="button1 "> request local text data < /button >
 < button id="button2 "> request local json data < /button >
 < button id="button3 "> request network interface < /button >
 <div id="output"></div>
 <script src="app.js"></script>

1.fetch requests local text data

There is a test.txt document locally, and the data can be obtained through the following code and displayed on the page.

 function getText(){
 . then((res) => res.text())// note: here is res.text ()
 .then(data => {
 document.getElementById('output').innerHTML = data;
 .catch(err => console.log(err));

2.fetch requests local JSON data

There is a posts.json data locally. Different from requesting local text, after getting the data, it is traversed by forEach and finally presented on the page.

 function getJson(){
 .then((res) => res.json())
 .then(data => {
 let output = '';
 data.forEach((post) => {
 output += `<li>${post.title}</li>`;
 document.getElementById('output').innerHTML = output;
 .catch(err => console.log(err));

3.fetch Request Network Interface

Obtain data in the is similar to the method of obtaining local JSON. After the data is obtained, it is also processed

 function getExternal(){
 .then((res) => res.json())
 .then(data => {
 let output = '';
 data.forEach((user) => {
 output += `<li>${user.login}</li>`;
 document.getElementById('output').innerHTML = output;
 .catch(err => console.log(err));