What is Axios?

Axios is a promise based web request library that works with Node.js and browsers. It is isomorphic (that is, the same set of code can run in the browser and node.js). On the server side it uses the native Node.js HTTP module, while on the client side it uses XMLHttpRequests.

features

  • Create XMLHttpRequests from the browser
  • Create HTTP requests from Node.js
  • Supporting Promise API
  • Intercept requests and responses
  • Transform request and response data
  • Cancel the request
  • Automatically convert JSON data
  • The client supports XSRF defense

Basic usage

It is used directly after import without any configuration

import axios from 'axios';

// Make a request to the user with the given ID
axios.get('/user? ID=12345')
  .then((response) = > {
    // Handle success
    console.log(response);
  })
  .catch((error) = > {
    // Handle error cases
    console.log(error);
  })
Copy the code

Regular use

Generally we use uniform configuration of interface baseUrl, timeout and so on in projects

import axios from 'axios';

const _axios = axios.create({
    baseUrl: 'http://localhost:9333/api'.timeout: 1000 * 15,})Copy the code

Configure the request interceptor

You can do some general configuration in the request interceptor, such as adding tokens to the request header or attaching some special common data

_axios.interceptors.request.use(config= >{
    / / add a token
    config.headers.token = 'token';
    // do something
},error= >Promise.reject(error))
Copy the code

Configure the return interceptor

You can do some general configuration in the request interceptor, such as adding tokens to the request header or attaching some special common data

_axios.interceptors.response.use(config= >{
    // do something
},error= >{
    // Do some uniform error handling
    // 401 requires authorization
    // The 404 interface does not exist
    // The request mode is not allowed, you used post instead of GET
    / / etc.
})
Copy the code

Cancel duplicate requests

In the project, we often encounter a button that is clicked quickly for many times in a row, so that we can request many times in a very short time. In fact, we only need to return the result once, and at this time, we can cancel the repeated submission for many times before.

Here we will use the axios.CancelToken method, which can be seen in the documentation

Encapsulate a method to cancel a request

class CancelToken {
  constructor() {
    this.store = new Map(a); } add (config) {const key = this.getKey(config);
      new axios.CancelToken((cancel) = > {
        if (this.store.has(key)) {
            this.remove(config)
        }
        this.store.set(key, cancel);
      });
  }
  remove (config)  {
      const key = this.getKey(config);
    if (this.store.has(key)) {
      let cancel = this.store.get(key);
      cancel(key);
      this.store.delete(key); }}// Get a unique key based on the request parameters
  getKey(config){
    const { method, url, params, data } = config;
    return [method, url, params, data].join(The '-'); }}Copy the code

Use the CancelToken method

const cancelToken = new CancelToken();
// Request interceptor
axios.interceptors.request.use(config= >{
    cancelToken.add(config);
},error= >Promise.reject(error))

// Receive interceptor
axios.interceptors.response.use(
    response= > {
        const config = response.config;
        cancelToken.remove(config)
        Promise.resolve(response)
    },
    error= > {
        return Promise.reject(error); });Copy the code

That concludes the general use of Axios, and thanks for reading.