Home >Web Front-end >JS Tutorial >An in-depth analysis of the process and principles of asynchronous requests in axios

An in-depth analysis of the process and principles of asynchronous requests in axios

藏色散人
藏色散人forward
2022-08-09 15:30:463294browse

1. What is axios?

axios is a Promise-based method that can send get, post and other requests, and can be used by both front and back ends. [Recommended: Ajax video tutorial, web front-end]

2. The internal principles of axios

  • axios library is exposed to the outside world An axios instance is mounted, and an Axios method is mounted in the axios instance. The Axios method has an interceptors object (interceptor), and the interceptors object has a request object and response object, and request object and response object both have use methods, so we can call axios.interceptors.request.use() and axios.interceptors .response.use().

  • ##interceptors objectThe request object and response object are actually a use To manage the array of interceptors (handlers). When we call axios.interceptors.request.use(), a success callback and a failure callback will be pushed in the request's interceptor array (handlers). Each time it is used, it is pushed once, similar to [res1, rej1, res2, rej2...]

  • The next is a chain,

    It is an array that stores all callbacks, Because it is used for Promise, it needs to use two values ​​, the initial values ​​are dispatchRequest and undefiend. Next, Promise.resolve(config).then(fn1, fn2). When the result in config is fulfilled (successful), the configuration in config is passed to fn1 and executed. If it is reject (error report), the error result is passed to fn2 and executed. That is, Promise.resolve(config).then(chain[0], chain[1]). chain[0] is a success callback, chain[1] is a failure callback. There are many configuration items in config, they may be a string value or method, etc.

  • The next step is to sort out all the Promises, unshift the callback function in the

    request array to the front of the chain array, and move ## The callback function in #response array is pushed to the end of chain array. The final chain array is similar to [res2, rej2, res1, rej1, dispatchRequest, undefiend, res3, rej3, res4, rej4].

  • dispatchRequest

    is used to execute axios.request, dispatchRequest method has an adapter, it will call different objects according to different environments. If it is in a browser environment, call the XMLHttpRequest object. If it is a nodejs environment, call http object. That's why it can be used on both the front-end and the back-end. adapter will parse and encapsulate the requested data, and the encapsulated object is the response response object we can see.

  • After processing
  • dispatchRequest

    , the callback function of interceptors.response will be executed. This is why the execution order we see is that the latter's interceptors.request is executed before the former's interceptors.requets, and then axios.request, Finally, execute interceptors.response.

  • in order and then execute our business logic.
  • 3. Use of axios

1. By using axios

Common methods: get, post, request

axios.get

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

axios.post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.request

can be passed in Many request configurations

axios.request({
	url: '/user',
	method: 'get', // 默认
	baseURL: '/api',
	//...})

2. Pass in the configuration method

axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
4. Response module

The response module has the following parameters

{
	data: {},
	status: 200,
	statusText: 'ok',
	header: {},
	config: {},
	request: {}}

5. Configuration

1. Global axios configuration

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

2. Instance configuration

const instance = axios.create({
  baseURL: 'https://api.example.com'});
 instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

3. Configuration priority

const instance = axios.create();instance.defaults.timeout = 2500;instance.get('/longRequest', {
  timeout: 5000});
The final timeout setting time is 5000, so the priority here is the configuration in the request>instantiation configuration>axios default configuration

6. Interceptors

Can process data before requesting data or before receiving data

axios.interceptors.request.use(function (config) {
    return config;
  }, function (error) {
    return Promise.reject(error);
  });
  axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    return Promise.reject(error);
  });

7. Concurrent request processing

// 把axios请求放进函数里function getUserAccount() {
  return axios.get('/user/12345');}
 function getUserPermissions() {
  return axios.get('/user/12345/permissions');}//函数执行放到Promise里面排队,挨个响应。Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

Reference document: https ://www.npmjs.com/package/axios

The above is the detailed content of An in-depth analysis of the process and principles of asynchronous requests in axios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete