The difference between ajax, axios, and fetch, finishing

Ajax(xhr)

AJAX Ajax is "AsynchronousJavascriptAndXML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications. It is a technique for updating parts of a web page without reloading the entire web page. Ajax enables web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a webpage can be updated without reloading the entire webpage. Traditional web pages (not using Ajax) must reload the entire web page if the content needs to be updated. Its disadvantages are as follows:

  • It is aimed at MVC programming and does not conform to the wave of front-end MVVM

  • Based on native XHR development, the structure of XHR itself is not clear

  • Does not comply with the principle of Separation of Concerns

  • The configuration and calling methods are very confusing, and the event-based asynchronous model is not friendly.

Ajax is a concept, a standard and a method. For example, jQuery has an encapsulated Ajax method to send get and post requests. The underlying principle is to use the XMLHttpRequest object. There is already Xhr2, which can transfer files, calculate upload progress and so on. Of course, Xhr can implement ajax by itself, but it is a little troublesome:

// 1. Create an instance of XMLHttpRequest 
let xhr = XMLHttpRequest() 
// 2. Open a connection with the server 
xhr.open('get', 'URL') 
// 3. Send 
xhr.send() 
// 4. Receive changes . 
xhr.onreadystatechange = () => { 
    if(xhr.readyState == 4 && xhr.status == 200){ // readyState: ajax status, status: http request status 
        console.log(xhr.responseText); // response subject 
    } 
}

TIPS (supplement: MVC and MVVM):

1. MVC (Model View Controller) is a software architecture pattern in software engineering, which divides the software system into three basic parts: model, view and controller . Organize the code with a method of separating business logic, data, and interface display, and gather business logic into one component. While improving and customizing the interface and user interaction, there is no need to rewrite the business logic.

2. MVVM is the abbreviation of Model-View-ViewModel, which is composed of three parts of MV-VM. It's essentially an improved version of MVC. MVVM is to abstract the state and behavior of the View, where the ViewModel separates the view UI from the business logic. It can take out the data of the Model and help deal with the business logic involved in the View due to the need to display content. With two-way data binding, data changes in the view will be automatically reflected on the viewmodel, and vice versa, data changes in the model will also be automatically displayed on the page. The ViewModel is what associates the Model with the View. ViewModel is responsible for synchronizing the data of the Model to the View for display, and is also responsible for synchronizing the modification of the View back to the Model.img

axios

Axios is an HTTP client based on Promise encapsulation, which is lighter than ajax in jq. It has two interceptors inside, namely request interceptor and response interceptor. In SPA applications, tokens are usually used for user identity authentication, which requires that each request must carry the user's identity information. For this requirement, in order to avoid separate processing in each request, we can package a unified request function to Add token information uniformly for every request. This is what interceptors do. Its characteristics are as follows:

  • The browser initiates an XMLHttpRequests request

  • The node side initiates an http request

  • Support Promise API

  • Listen for requests and returns

  • Convert requests and returns, automatically convert json data

  • Client supports defense against CSRF attacks

The commonly used methods of axios are get, post, put, patch, deleteand so on. Wherein getand postreturned are promiseobjects, promisemethods can be used. At present, there are many strange ones used in vue. Example of get method:

axios.get('apiURL', {
    param: {
        id: 1
    }
    // param 中的的键值对最终会 ? 的形式,拼接到请求的链接上,发送到服务器。
}).then(res => {
    console.log(res);
})
.catch( error => {
    console.log(error)
}

Knowledge points about axios:

Axios interceptor execution sequence:

//添加两个请求拦截,看到时候先执行哪个
axios.interceptors.request.use(config => {
  console.log(`请求1`);
  return config;
});
axios.interceptors.request.use(config => {
  console.log(`请求2`);
  return config;
});
​
//添加两个响应拦截,看到时候先执行哪个
axios.interceptors.response.use(response => {
  console.log(`响应1`);
  return response.data;
});
axios.interceptors.response.use(response => {
  console.log(`响应2`);
  return response;
});
​
// 发送请求 
axios.get('/posts')
  .then(response => {
    console.log('success');
  }) 
​
//**************结果*********************//
console.log("请求2");
console.log("请求1");
console.log("响应1");
console.log("响应2");
console.log("success");
//原因,请求拦截使用的是数组的unshift方法,响应拦截使用的是push方法

fetch

fetch claims to be a substitute for AJAX, which appeared in ES6 and uses the promise object in ES6. Fetch is designed based on promises. The code structure of Fetch is much simpler than that of ajax. fetch is not a further encapsulation of ajax, but native js, without using the XMLHttpRequest object. fetchIt is the way of http request data, it uses Promise, but does not use callback function. fetchIt adopts a modular design and processes data through data streams, which is very useful for requests for large files or slow network speeds. By default fetch will not receive or send cookies.

  • Concise syntax, more semantically based on standards

  • Promise implementation, support async/await

  • It is more low-level and provides rich APIs (request, response)

  • Separated from XHR, it is a new implementation in the ES specification

shortcoming:

  • Too low-level, many status codes are not encapsulated. Only report errors for network requests, and treat 400 and 500 as successful requests.

  • Unlike XHR, fetch cannot detect request progress.

  • The request cannot be blocked, and the request process continues to run in the background, resulting in a waste of traffic. Does not support abort, does not support timeout control, use setTimeout and Promise.reject to achieve timeout control.

  • poor compatibility

 

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129079176
Recommended