The article directories

  • What does Axios do
  • Native XMLHttpRequest implementation
  • Axios introduction
    • Sending concurrent requests
  • axios API
    • Create an instance
    • Config Configuration options
    • The default Settings
      • Global Default Settings
      • Custom defaults in the instance
      • Priority set
    • Response Schema
    • The interceptor interceptors
    • Error handling
    • Cancel the request

What does Axios do

When the old browser page requests data from the server, the page is forced to refresh because it returns data from the entire page, which is not very user friendly. And we only need to modify part of the page data, but sent from the server is the whole page data, very consumption of network resources. We only need to modify part of the page, and we don’t want to refresh the page, so asynchronous network requests come into being.

Asynchronous JavaScript and XML: Asynchronous network requests. Ajax enables pages to be free of refreshed request data.

Ajax can be implemented in many ways, such as Jquery-wrapped Ajax, native XMLHttpRequest, and Axios. But there are pros and cons to each approach

  1. Native XMLHttpRequest is cumbersome to configure and invoke, making asynchronous requests cumbersome
  2. JQuery ajax is quite handy compared to native Ajax, but there is no need to reference the jQuery framework to use Ajax for asynchronous network requests

Axios, which stands for Ajax I/O System, is not a new technology and is essentially a wrapper around native XMLHttpRequest, available in browsers and HTTP clients for NodeJS, but it’s based on Promise and complies with the latest ES specification. It has the following characteristics:

  1. Create an XMLHttpRequest request in your browser
  2. Send HTTP requests in Node.js
  3. Supporting Promise API
  4. Intercept requests and responses
  5. Transform request and response data
  6. Cancel the request
  7. Automatically convert JSON data
  8. Client support to prevent CSRF/XSRF(Cross-domain request forgery)

Native XMLHttpRequest implementation

Native XMLHttpRequest implements Ajax requests

var request = new XMLHttpRequest(); // Create an XMLHttpRequest object
// Ajax is asynchronous, set the callback function
request.onreadystatechange = function () { // The function is called back when the state changes
    if (request.readyState === 4) { // Completed successfully
        // Determine the response status code
        if (request.status === 200) {
            // Get the text of the response via responseText:
            return success(request.responseText);
        } else {
            // Failed, according to the response code to determine the failure cause:
            returnfail(request.status); }}else {
        // HTTP requests continue...}}// Send a request:
request.open('GET'.'/api/categories');
request.setRequestHeader("Content-Type"."application/json") // Set the request header
request.send();// At this point, the request is officially issued

   
Copy the code

Axios introduction

Axios is based on Promises, so you can use the Promise API

Axios requests:

  1. axios(config)
  2. axios.request(config)
  3. axios.get(url [,config])
  4. axios.post(url [,data [,config]])
  5. axios.put(url [,data [,config]])
  6. axios.delete(url [,config])
  7. axios.patch(url [,data [,config]])
  8. axios.head(url [,config])
// Execute the GET request
import axios from 'axios'
axios.default.baseURL = 'http://localhost:3000/api/products'
axios.get('/user? ID=12345')  // Return a Promise
    .then(res= >console.log(res))
    .catch(err= >console.log(err));
Copy the code

Axios.get (‘ /user ‘,{params:{ID:12345}}).then(res=>console.log(res)).catch(err=>console.log(err));

// Send a POST request
axios.post('/user', {firstName: 'simon'.lastName:'li'
}).then(res= >console.log(res))
    .catch(err= >console.log(err));
Copy the code

Sending concurrent requests

Axios.all (iterable) allows you to send multiple requests, not necessarily an array, as long as you have an iterable interface. The function returns an array

Axios.spread (callback) can be used to expand the result array

// Send multiple requests (concurrent requests), similar to promise.all, if one request fails, the request will be stopped
const get1 = axios.get('/user/12345');
const get2 = axios.get('/user/12345/permission');
axios.all([get1,get2])
    .then(axios.spread((res1,res2) = >{
    	console.log(res1,res2);
	}))
    .catch(err= >console.log(err))

 
Copy the code

axios API

Axios (config) can send the request by setting some properties

// Send a POST request
axios({
    method: 'post'.// Request mode, default is get request
    url:'/user/12345'./ / address
    data: {/ / parameters
        firstName: 'simon'.lastName: 'li'}});Copy the code

Create an instance

You can use axios,create([config]) to create a new instance and set the related properties

const instance = axios.create({
    baseURL: 'http://localhost:3000/api/products'.timeout: 1000.headers: {'X-Custom-Header':'foobar'}});/ / the use of the instance
instance.get('/user', {params: {ID:12345}
}).then(res= >console.log(res))
.catch(err= >console.log(err))

 
Copy the code

Config Configuration options

{
    // The server address is required
    url: '/user'.<span class="token comment">// Request mode, if there is no default get</span>
method<span class="token punctuation"> : </span><span class="token string">'get'</span><span class="token punctuation">.</span>
    
<span class="token comment">// If the URL is not an absolute address, baseURL is added</span>
baseURL<span class="token punctuation"> : </span> <span class="token string">'http://localhost:3000///transformRequest allows requested data to be processed before being sent to the server.  ArrayBuffer'or'Stream'or'Buffer'Instance or'ArrayBuffer', 'Formdata'</span> <span class="token comment"> Set the headers attribute </ SPAN > transformRequest< SPAN class="token punctuation">:</ SPAN > < SPAN class="token punctuation">[</span><span class="token keyword">function</span><span class="token punctuation">(</span>data<span class="token punctuation">,</span>headers<span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> <span class="token comment">// Process data according to requirements </span> < SPAN class="token keyword">return</span> data<span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">]</span><span Class ="token punctuation">,</span> <span class="token comment"> transformResponse<span class="token punctuation">:</span><span class="token punctuation">[</span><span class="token keyword">function</span><span class="token punctuation">(</span>data<span class="token punctuation">)</span><span Class ="token punctuation">{<!-- --></span> <span class="token comment">// Process the data as needed </span> <span class="token keyword">return</span> data<span class="token punctuation">;</span> <span class="token punctuation">}</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token Comment ">//headers is a user-defined message header to be sent. </span> headers< SPAN class="token punctuation">:</span> <span class="token punctuation">{<! -- --></span><span class="token string">'X-Requested-with'</span><span class="token punctuation">:</span><span class="token string">'XMLHttpRequest'</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token Comment "> < span style = "box-sizing: border-box; Must be a pure object </span> params<span class="token punctuation">:</span><span class="token punctuation">{<! -- --></span> <span class="token constant">ID</span><span class="token punctuation">:</span><span class="token number">12345</span> <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token Comment ">//paramsSerializer is used to serialize parameters. </ SPAN > paramsSerializer< SPAN class="token punctuation">:</span> < SPAN class="token keyword">function</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span><span class="token punctuation">{<! -- --></span> <span class="token keyword">return</span> Qs<span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>params<span class="token punctuation">,</span><span class="token punctuation">{<! -- --></span>arrayFormat<span class="token punctuation">:</span><span class="token string">'brackets'</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">; </span> <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token Request. Body </ SPAN > < SPAN class="token comment">// Applies only to put, POST, and patch requests </span> <span Class ="token comment">// FormData, File, Blob; Node:stream</span> data<span class="token punctuation">:</span><span class="token punctuation">{<! -- --></span> firstName<span class="token punctuation">:</span> <span class="token string">'West Gate'</span><span class="token punctuation">,</span> <span class="token punctuation">}</span><span class="token Punctuation ">,</span> <span class="token comment">//timeout Specifies the length of the request in milliseconds. The request will stop </ SPAN > timeout< SPAN class="token punctuation">:</span>< SPAN class="token number">1000</span>< SPAN class="token Punctuation ">,</span> <span class="token comment">//withCredentials indicate whether authentication is required across domains. </span> withCredentials<span class="token punctuation">:</span><span class="token boolean">false</span><span </span> <span class="token comment">// Default </span> <span class="token comment"> Allows custom processing of requests </ SPAN >< SPAN class="token comment">// Returns a promise</span> Adapter < SPAN class="token punctuation">:</span>< SPAN class="token keyword">function</span><span class="token punctuation">(</span>config<span class="token punctuation">)</span><span class="token punctuation">{<! -- --></span> <span class="token comment">/*... */</span> <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token Comment ">//auth indicates that HTTP-based authentication should be used, </span> auth< SPAN class="token punctuation">:</span>< SPAN class="token punctuation">{<! -- --></span> username<span class="token punctuation">:</span><span class="token string">'West Gate', password:'123456', }, //responseType Specifies the type of data returned by the server. json/blob/document/ arraybuffer/text/stream  responseType: 'json'< SPAN class="token comment">//proxy Specifies the host name and port number of the server  // The auth attribute indicates that HTTP basic authentication should be connected to the proxy and provide a certificate.Proxy-AuthorizationProxy <span class="token punctuation">:</span><span class="token punctuation">{<! -- --></span> host<span class="token punctuation">:</span><span class="token number">127.0</span><span class="token number">.0</span><span class="token number">.1</span><span class="token punctuation">,</span> port<span class="token punctuation">:</span><span class="token number">8080</span><span class="token punctuation">,</span> auth<span class="token punctuation">:</span><span class="token punctuation">{<! -- --></span> username<span class="token punctuation">:</span><span class="token string">'West Gate', password:'123456'</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span><span class="token Punctuation ">,</span> <span class="token comment"> <span class="token keyword">new</span> <span class="token class-name">CancelToken</span><span class="token punctuation">(</span>cancel<span class="token operator">=&gt; </span><span class="token punctuation">{<! -- --></span><span class="token punctuation">}</span><span class="token punctuation">)</span>Copy the code

}

}

Get (‘ /user/12345 ‘). Then (response={console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); })

The interceptor interceptors

Interceptor intercepts requests or responses before they are processed by THEN or catch. After intercepting, the data can be processed, such as adding headers to the request data, or serializing the response data before passing it to the browser

// Add a request interceptor
axios.interceptors.request.use(config= >{
    // Do something before you ask
    return config;
},err= >{
   // Do something when the request is wrong
    return Promise.reject(err);
});
Copy the code

/ / add a response to the interceptor axios. Interceptors. Response. Use (response = > {/ / do some with the data returned reutrn response; },err=>{// Do something about returned errors return promise.reject (err); });

// Remove interceptor
const myInterceptor = axios.interceptors.request.use(config= >{return cofig})
axios.interceptors.request.eject(myInterceptor);
Copy the code

// Use the interceptor in an axios instance var instance = axios.create(); The instance. The interceptors. Request. Use (function () {/… /});

Error interception is rare in request interception and is usually configuration dependent

In response interception, if successful, it mainly filters the data. If the error message fails, starus can determine the status code of the error message and go to a different error page

Error handling

Use the validateStatus setting option to customize the error range for the HTTP status code

axios.get('user/12345', {validateStatus:function(status){
        return status < 500;If the return code is less than or equal to 500, it is an error}});"> < p style = "max-width: clear; clear: both; min-height: 1pt; clear: both; min-height: 1pt; Therefore, the request needs to be cancelled. const CancelToken = axios.CancelToken; Canceltoken.source const source = canceltoken.source (); canceltoken.source ();Copy the code

Axios. Get (/ user / 12345 ‘, ‘{cancelToken: Toke}). Catch (thrown=>{if(axios.iscancel (thrown)){console.log(‘ Request Canceled ‘, logo.message); }else{ //handle error } });

// Cancel the request source.cancel(‘ operation cancelled by user ‘);

Reference link: www.axios-js.com/docs/index….