1, ajax

Native Ajax creation

//1. Create an Ajax object
 var xhr=new XMLHttpRequest();
//2. Connect to server (open connection to server)
xhr.open('GET', url, true); 
/ / 3. Send
xhr.send(); 
/ / 4. Receive
xhr.onreadystatechange=function (){ 
    if(oAjax.readyState==4) {if(oAjax.status==200) {/ / success
            fnSucc(xhr.responseText); 
         }else{ 
             //alert(' failed ');
             if(fnFaild){ fnFaild(); }}}}Copy the code

2, axios

axios({
    method: 'post'.url: '/user/12345'.data: {
        firstName: 'Sue'.lastName: 'S'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
Copy the code

Axios is essentially a wrapper around native XHR, just a version of Promise that complies with the latest ES specification. The following features can be seen on the website:

  • Create an HTTP request from Node.js
  • Supporting Promise API
  • The client supports CSRF prevention
  • Provides several interfaces for concurrent requests

To prevent CSRF attack implementation principle: in each request with a cookie to get the key, according to the browser’s same-origin policy, the fake website is unable to get the key in the cookie, so that the background can easily identify whether the request is the user in the fake website misleading input to take the correct strategy

3, the fetch


fetch(url, {
  method: "POST".body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     / / = > number 100-599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  return response.text()
}, function(error) {
  error.message //=> String
})
Copy the code

Fetch document link: github. Github. IO /fetch/

Advantages of FETCH:

  • The syntax is concise and more semantic
  • Promise based implementation with support for async/await
  • Closer to the bottom, providing rich apis
  • XHR is a new implementation of the ES specification
  • Cross-domain processing credentials: "same-origin"

Disadvantages of FETCH:

  • Fetch only reports errors for network requests. 400,500 requests are considered successful and need to be encapsulated for processing
  • Fetch does not contain cookies by default, and configuration items need to be added
  • Fetch does not support abort and timeout control. Timeout control implemented with setTimeout and promise. reject does not prevent the request process from running in the background, resulting in wasted traffic
  • Fetch has no way to natively monitor the progress of requests, whereas XHR can

Reference links: segmentfault.com/a/119000001…