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();
 xhr.open('GET', url/file,true);
 xhr.onreadystatechange = function() {
 if(xhr.readyState==4){
 if(xhr.status==200){
 var data=xhr.responseText;
 console.log(data);
 }
 };
 xhr.onerror = function() {
 console.log("Oh, error");
 };
 xhr.send();

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.
Promise工作原理

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 >
 <br><br>
 <div id="output"></div>
 </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.

document.getElementById('button1').addEventListener('click',getText);
 function getText(){
 fetch("test.txt")
 . then((res) => res.text())// note: here is res.text ()
 .then(data => {
 console.log(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.

document.getElementById('button2').addEventListener('click',getJson);
 function getJson(){
 fetch("posts.json")
 .then((res) => res.json())
 .then(data => {
 console.log(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

Obtainhttps://api.github.com/usersThe data in the is similar to the method of obtaining local JSON. After the data is obtained, it is also processed

document.getElementById('button3').addEventListener('click',getExternal);
 function getExternal(){
 //  https://api.github.com/users
 fetch("https://api.github.com/users")
 .then((res) => res.json())
 .then(data => {
 console.log(data);
 let output = '';
 data.forEach((user) => {
 output += `<li>${user.login}</li>`;
 })
 document.getElementById('output').innerHTML = output;
 })
 .catch(err => console.log(err));
 }