Axios

Introduction to the

Axios is a Promise-based HTTP client that supports both browsers and Node.js. Has the following features:

  • Supports AJAX requests sent by browsers
  • Supports Node.js to send HTTP requests
  • Supporting Promise
  • Intercept requests and responses
  • Transform the request and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF attacks

An introduction to intercepting requests and responses

When the front end sends a request to the back end, many of the configuration parameters and processing of the request return are the same. If you configured the same parameters and added request handlers to every HTTP request, the code would look ugly and difficult to maintain.

Imagine the following scenario

  • Application jWT-BASED authentication is required on each HTTP requestHeaderTo addtoken.
  • For returned error messages, unified error handling is performed

Axios provides a solution to the above problem scenario, an interceptor.

Use interceptors

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});
Copy the code

Realize the principle of

Question:

  • When does the interceptor handler fire?

Axios instance object

Through axios. Interceptors. Request. Use () call interceptor, learned that the interceptor is axios instance properties.

In the following code, the Axios constructor has the property Interceptors. The request and Response properties of the interceptors are instance objects of the InterceptorManager class

// lib/core/Axios.js

function Axios(instanceConfig) {
  this.defaults = instanceConfig;
  this.interceptors = {
    request: new InterceptorManager(),
    response: new InterceptorManager()
  };
}
Copy the code

Interception handler collection

The InterceptorManager class is used to generate an interceptor instance. The Use method is primarily used to add handlers to the Promise success and failure states

// lib/core/InterceptorManager.js

function InterceptorManager() {
  this.handlers = [];
}

/**
 * Add a new interceptor to the stack
 *
 * @param {Function} fulfilled The function to handle `then` for a `Promise`
 * @param {Function} rejected The function to handle `reject` for a `Promise`
 *
 * @return {Number} An ID used to remove interceptor later
 */
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  this.handlers.push({
    fulfilled: fulfilled,
    rejected: rejected
  });
  return this.handlers.length - 1;
};
Copy the code

Intercepting request and response triggering

Axios request method, the call will trigger the interceptor axios support the request of the method is as follows, these methods will be called last axios. Request. Axios. Request to trigger the request and response interceptor and sending HTTP requests to the server.

  • 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]])
// lib/core/Axios.js

// Provide aliases for supported request methods
utils.forEach(['delete'.'get'.'head'.'options'].function forEachMethodNoData(method) {
  /*eslint func-names:0*/
  Axios.prototype[method] = function(url, config) {
    return this.request(mergeConfig(config || {}, {
      method: method,
      url: url,
      data: (config || {}).data
    }));
  };
});

utils.forEach(['post'.'put'.'patch'].function forEachMethodWithData(method) {
  /*eslint func-names:0*/
  Axios.prototype[method] = function(url, data, config) {
    return this.request(mergeConfig(config || {}, {
      method: method,
      url: url,
      data: data
    }));
  };
});
Copy the code

axios.request

DispatchRequest is used to send HTTP requests, with request interceptor handlers placed before the method and response interceptor handlers placed after it.

// lib/core/Axios.js
/**
 * Dispatch a request
 *
 * @param {Object} config The config specific for this request (merged with this.defaults)
 */
Axios.prototype.request = function request(config) {
  /*eslint no-param-reassign:0*/
  // Allow for axios('example/url'[, config]) a la fetch API
  if (typeof config === 'string') {
    config = arguments[1) | | {}; config.url =arguments[0];
  } else {
    config = config || {};
  }

  config = mergeConfig(this.defaults, config);

  // Set config.method
  if (config.method) {
    config.method = config.method.toLowerCase();
  } else if (this.defaults.method) {
    config.method = this.defaults.method.toLowerCase();
  } else {
    config.method = 'get';
  }

  // Hook up interceptors middleware
  var chain = [dispatchRequest, undefined];
  var promise = Promise.resolve(config);

  this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
    chain.unshift(interceptor.fulfilled, interceptor.rejected);
  });

  this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
    chain.push(interceptor.fulfilled, interceptor.rejected);
  });

  while (chain.length) {
    promise = promise.then(chain.shift(), chain.shift());
  }

  return promise;
};
Copy the code

reference

  • Juejin. Cn/post / 688547…
  • medium.com/@monkov/rea…