Axios explained in detail

Article Directory

  • I. Introduction to axios
    • 1.1. Features
    • 1.2. Install
  • II. Examples
    • 2.1. Send a GET request
    • 2.2. Send a POST request
    • 2.3. disposable Concurrent multiple requests
  • III. Axios APIs
    • 3.1. Axios can send requests via config
    • 3.2. Alias for request mode
    • 3.3. Concurrent request (concurrency) is an auxiliary function to help process concurrent requests.
    • 3.4. Create a axios instance and customize its configuration
  • IV. Requested Configuration Object config Description
    1. Contents returned after the request succeeds
    1. Default Global Configuration
    1. Custom Instance Default Settings
  • VIII. Priority in configuration
  • IX. Interceptor
    • 9.1. Request Blocker and Response Blocker
    • 9.2. Unblocker
    • 9.3. Adding a Blocker to a Custom axios Instance
  • X. Error Handling
  • Xi. Cancellation Request
    • 11.1. Method 1
    • 11.2. Method 2

I. Introduction to axios

Axios is a network request library based on Promise, which is used in nodejs and browser. The server uses the http module in the native node to send the request, and the browser uses the XMLHttpRequest request.

1.1. Features

  • Browser and node.js support
  • Support for promise
  • Ability to block requests and responses
  • Ability to convert request and response data
  • Can cancel request
  • Automatically convert JSON data
  • Browser-side support for CSRF prevention(Cross-site request forgery)

1.2. Install

  • Install
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 
``` with 

```javascript
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 
  • Install
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 
``` with 

```javascript
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 
  • Introduce
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 
``` directly with 

```javascript
axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 

II. Examples

2.1. Send a GET request

axios
  .get("/user?ID=12345")
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 

The above request can also be sent in this way

axios
  .get("/user", {
    params: {
      ID: 12345,
    },
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (err) {
    console.log(err);
  }); 

2.2. Send a POST request

axios
  .post("/user", {
    firstName: "Fred",
    lastName: "Flintstone",
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (err) {
    console.log(err);
  }); 

2.3. disposable Concurrent multiple requests

function getUserAccount() {
  return axios.get("/user/12345");
}
function getUserPermissions() {
  return axios.get("/user/12345/permissions");
}
axios.all([getUserAccount(), getUserPermissions()]).then(
  axios.spread(function (acct, perms) {
    //This function will be triggered when both requests are completed.,The two parameters represent the returned results respectively.
  })
); 

III. Axios APIs

3.1. Axios can send requests via config

  • axios(config)
//send a`POST`ask
axios({
  method: "POST",
  url: "/user/12345",
  data: {
    firstName: "Fred",
    lastName: "Flintstone",
  },
}); 
  • axios(url[,config])
//send a`GET`ask(Default request method)
axios("/user/12345"); 

3.2. Alias for request mode

Note: When we are using the alias method, url,method,data these parameters do not need to be declared in the configuration

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]]) 

3.3. Concurrent request (concurrency) is an auxiliary function to help process concurrent requests.

//iterableIs an iterable parameter such as an array, etc.
axios.all(iterable);
//callbackWait until all requests are completed before executing
axios.spread(callback); 

3.4. Create a axios instance and customize its configuration

  • axios.create([config])
const instance = axios.create({
  baseURL: "https://some-domain.com/api/",
  timeout: 1000,
  headers: { "X-Custom-Header": "foobar" },
}); 

IV. Requested Configuration Object config Description

That is, what properties can be customized for the config configuration object in the axios(config)? The following are the requested configuration options. Only the url option is required. If the method option is not defined, the request is made in the GET mode by default.

{
  //`url`is the requested server address
  url: "/user",
  //`method`is the way to request resources
  method: "get", //default
  //if`url`Not an absolute address,So`baseURL`will be added to`url`in front of
  //when`url`When it is a relative address,set up`baseURL`It will be very convenient
  baseURL: "https://some-domain.com/api/",
  //`transformRequest`Options allow us to make some changes to the requested data before the request is sent to the server
  //This option is only available for the following request methods:`put/post/patch`
  //The last function in the array must return a string、-one`ArrayBuffer`or`Stream`
  transformRequest: [
    function (data) {
      //Change the data here according to your needs
      return data;
    },
  ],
  //`transformResponse`option allows us to transfer data to`then/catch`Modify data before method
  transformResponse: [
    function (data) {
      //Change the data here according to your needs
      return data;
    },
  ],
  //`headers`Options are custom request headers that need to be sent
  headers: { "X-Requested-With": "XMLHttpRequest" },
  //`params`Options are request parameters to be sent with the request----General links are atURLlater
  //Its type must be a pure object orURLSearchParamsobject
  params: {
    ID: 12345,
  },
  //`paramsSerializer`is an optional function,What works is to let the parameters(params)Serialization
  //For example(https://www.npmjs.com/package/qs,http://api.jquery.com/jquery.param)
  paramsSerializer: function (params) {
    return Qs.stringify(params, { arrayFormat: "brackets" });
  },
  //`data`Options are the data that need to be sent as a request body
  //This option only applies to methods:`put/post/patch`
  //when not set`transformRequest`optiondadaMust be one of the following types
  //string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
  //browser only:FormData/File/Bold
  //onlynode:Stream
  data: {
    firstName: "Fred",
  },
  //`timeout`Option defines the number of milliseconds to delay the request from being issued
  //If the request takes longer than the delay,then the request will be terminated

  timeout: 1000,
  //`withCredentails`The option indicates whether it is a cross-domain request

  withCredentials: false, //default
  //`adapter`Adapter options allow custom handling of requests,This will make testing easier
  //Return apromise,and provide verification returns
  adapter: function (config) {
    /*..........*/
  },
  //`auth`showHTTPBasic authentication should be used,and provide certificate
  //This will set aauthorizationhead(header),and cover you inheadersetAuthorizationheader information
  auth: {
    username: "zhangsan",
    password: "s00sdkf",
  },
  //Return data format
  //The options arearraybuffer,blob,document,json,text,stream
  responseType: "json", //default
  //
  xsrfCookieName: "XSRF-TOKEN", //default
  xsrfHeaderName: "X-XSRF-TOKEN", //default
  //`onUploadProgress`Upload progress event
  onUploadProgress: function (progressEvent) {},
  //Download progress events
  onDownloadProgress: function (progressEvent) {},
  //The maximum value of the corresponding content
  maxContentLength: 2000,
  //`validateStatus`defined whether based onhttpCorresponding status code,Comeresolveorreject promise
  //if`validateStatus`returntrue(Or set to`null`or`undefined`),SopromiseThe status will beresolved,Otherwise its status isrejected
  //Not configured by defaultstatus >= 200 && status < 300yesresolvedOtherwise its status isrejected
  validateStatus: function (status) {
    return status >= 200 && status < 300; //default
  },
  //`maxRedirects`defined innodejsThe maximum number of redirects in
  maxRedirects: 5, //default
  //`httpAgent/httpsAgent`Defines when to sendhttp/httpsRequest a custom proxy to use
  //keeyAliveNot activated by default in options
  httpAgent: new http.Agent({ keeyAlive: true }),
  httpsAgent: new https.Agent({ keeyAlive: true }),
  //proxyHost name and port number defined,
  //`auth`showhttpBasic authentication should be done withproxyproxy link,and provide certificate
  //This will set a`Proxy-Authorization` header,and will overwrite existing ones`Proxy-Authorization`  header
  proxy: {
    host: "127.0.0.1",
    port: 9000,
    auth: {
      username: "skda",
      password: "radsd",
    },
  },
  //`cancelToken`Defines a function for canceling requestscancel token
  //See detailscancelationpart
  cancelToken: new cancelToken(function (cancel) {}),
}; 

5. Contents returned after the request succeeds

{
  // `data` response provided by the server,will automatically resolve tojsonFormat
  data: {},

  // `status` response from server HTTP status code
  status: 200,

  // `statusText` response from server HTTP status information
  statusText: "OK",

  // `headers` Is the server response header
  // all header Names are all lowercase,And can be accessed using square bracket syntax
  // For example: `response.headers['content-type']`
  headers: {},

  // `config` yes `axios` Requested configuration information
  config: {},

  // `request` is the request that generated this response
  // existnode.jsit&#39;s the last oneClientRequestExample (in redirects),
  // In the browser it is XMLHttpRequest Example
  request: {},
}; 

6. Default Global Configuration

//Request base address,For example, set it as follows,Then we are configuringurlWhen using attributes, you only need to write the content after the base address.
//url: 'http://localhost:3000/title' => url: /title
axios.defaults.baseURL = 'https://localhost:3000';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
//Content-TypeTo represent the media type information in the specific request,To be precise, the client tells the server,
//The type of data structure carried in the request message you are about to send.,So that the server can process it in an appropriate way after receiving it.。
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//Request type
axios.defaults.method = 'get';
//`validateStatus`defined whether based onhttpCorresponding status code,Comeresolveorreject promise
//if`validateStatus`returntrue(Or set to`null`or`undefined`),SopromiseThe status will beresolved,Otherwise its status isrejected
//Not configured by default2xxthink soresolvedOtherwise its status isrejected
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 299; 
}; 

7. Custom Instance Default Settings

// Configure default values ​​when creating an instance
const instance = axios.create({
  baseURL: 'https://localhost:3000'
});
// Modify the default value after creating the instance
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

//use it
instance({
  method: 'get',
  url: '/title/1'
}).then(res => {
  console.log(res)
}) 

VIII. Priority in configuration

axios
.post("/user", {
firstName: "Fred",
lastName: "Flintstone",
})
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log(err);
});
``` configuration will be merged in priority

> Configuration of the `config` parameter in the request

```javascript
//Used when creating an instancelibrayDefault configuration in directory
//it's heretimeoutThe configured value is0,FromlibrayThe default value of
var instance = axios.create();
//overwritelibraryThe default value of
//All requests now have to wait2.5SWill be sent out later
instance.defaults.timeout = 2500;
//heretimeoutBack to overwriting the previous2.5Sbecome5s
instance.get("/longRequest", {
timeout: 5000,
});
</code></pre>

<h2>IX. Interceptor</h2>

<h3>9.1. Request Blocker and Response Blocker</h3>

<ul>
<li>The request and response interceptors have success and failure callback functions respectively.</li>
<li>When the request fails to be intercepted, the corresponding response interceptor executes the callback of the response failure.</li>
</ul>

<pre><code class="language-javascript line-numbers">// Add request interceptor
axios.interceptors.request.use(function (config) {
// What to do before sending a request
return config;
}, function (error) {
// What to do about request errors
return Promise.reject(error);
});

// Add response interceptor
axios.interceptors.response.use(function (response) {
// 2xx Any status code within the range will trigger this function。
// Do something with the response data
return response;
}, function (error) {
// beyond 2xx This function will be triggered by any status code in the range。
// Do something about the response error
return Promise.reject(error);
});
</code></pre>

<h3>9.2. Unblocker</h3>

<pre><code class="language-javascript line-numbers">var myInterceptor = axios.interceptors.request.use(function () {
/*....*/
});
axios.interceptors.request.eject(myInterceptor);
</code></pre>

<h3>9.3. Adding a Blocker to a Custom axios Instance</h3>

<pre><code class="language-javascript line-numbers">var instance = axios.create();
instance.interceptors.request.use(function () {});
</code></pre>

<h2>X. Error Handling</h2>

<pre><code class="language-javascript line-numbers">axios.get("/user/12345").catch(function (error) {
if (error.response) {
//Request has been sent,But is the status returned by the server response different?2xxIn the range
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.header);
} else {
//Some errors are triggered when setting up the request
console.log("Error", error.message);
}
console.log(error.config);
});
</code></pre>

<h2>Xi. Cancellation Request</h2>

<h3>11.1. Method 1</h3>

You can create a <code>cancel token</code> through the <code>CancelToken.source</code> factory function

<pre><code class="language-javascript line-numbers">var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios
.get("/user/12345", {
cancelToken: source.token,
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log("Request canceled", thrown.message);
} else {
//handle error
}
});

//Cancel request(Information parameters can be set)
source.cance("Operation canceled by user");
</code></pre>

<h3>11.2. Method 2</h3>

<blockquote>
You can pass a <code>executor function</code> constructor to create a <code>cancel token</code>
</blockquote>

<pre><code class="language-javascript line-numbers">var cancelToken = axios.CancelToken;
var cance;
axios.get("/user/12345", {
cancelToken: new CancelToken(function (c) {
//thisexecutorThe function accepts acancel functionas parameter
cancel = c;
}),
});
//Cancel request
cancel();
</code></pre>

This document is transferred from

```objective-c
function getUserAccount() {
return axios.get("/user/12345");
}
function getUserPermissions() {
return axios.get("/user/12345/permissions");
}
axios.all([getUserAccount(), getUserPermissions()]).then(
axios.spread(function (acct, perms) {
//This function will be triggered when both requests are completed.,The two parameters represent the returned results respectively.
})
);
```.