MEMEPh. ideas that are worth sharing...

How fetch requests data

A preface


In the traditional Ajax era, network requests such as APIs are made through XMLHttpRequest or the encapsulated framework. However, the configuration and invocation methods are very confusing, which is not friendly to newcomers. Fetch, which we introduce today, provides a better alternative that not only provides an easy, logical way to fetch resources asynchronously across the network, but can easily be used by other technologies such as Service Workers.

 

2. Comparison with Ajax


Using Ajax to request a JSON data generally 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();

Again we use fetch to request JSON data:

fetch(url).then(response => response.json())//parse into readable data
.then(data => console.log(data))//The execution result is resolve and the then method is called
.catch(err => console.log("Oh, error", err))//If the execution result is reject, call the catch method

From the comparison of the two, the fetch code is much simpler and the business logic is clearer, making the code easier to maintain and more readable.

 

All in all, the main advantages of Fetch are:

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

2. Based on standard Promise implementation, support async/await

3. Isomorphic convenience, use isomorphic-fetch

 

3. Introduction to Three Promises


Since the Fetch API is based on the Promise design, let's briefly introduce the Promise workflow so that you can better understand Fetch.

 

How Promises Work

The fetch method returns a Promise object. According to the characteristics of the Promise Api, fetch can easily use the then method to string together various processing logics. Using the Promise.resolve() or Promise.reject() methods will return a positive or negative Promise respectively. The resulting Promise, which calls the next then or catch. Once the statement in then has an error, it will also jump to the catch.

 

4. request common data format


Next, we will describe 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 part
<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 request local text data

There is a test.txt document locally, and the data in it can be obtained by 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 request local JSON data

There is a posts.json data locally. Different from requesting local text, it needs to be traversed with forEach after getting the data, and finally rendered 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

The data being obtained https://api.github.com/usersis similar to the method of obtaining local JSON. After the data is obtained, it must also be 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));
}