What is Axios?

Axios is a Promise-based HTTP library that can be used in browsers and Node.js. Chinese official website

features

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

The installation

NPM: NPM install axios yarn: yarn add axios CDN: < script SRC = “https://unpkg.com/axios/dist/axios.min.js” > < / script >

Create instance axios.create(config)

// Create an axios instance
const http = axios.create({
  baseURL: baseUrl, // baseUrl
  timeout: 5000 // The timeout period
  // More configuration items can be seen on the official website
})
Copy the code

The interceptor

Intercept requests or responses before they are processed by THEN or catch, and then do something indescribable to them.

Request interceptor

// Add request interceptor
axios.interceptors.request.use(function(config) {
    // What to do before sending the request
    config.headers = {
        'content-type': 'application/json'.'token': getToken()
    }
    return config;
}, function (error) {
    // Request error
    return Promise.reject(error);
});
Copy the code

Response interceptor

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with the returned data such as state interception
    if(response.data.status ! = =200) {
        Toast({
          message: response.data.message,
          type: 'warning'.duration: 1000
        })
        return
      }
      
    // No problem
    return response.data;
}, function (error) {
    // Response error
    return Promise.reject(error);
});
Copy the code

Instance adds interceptors

// Instances can also add interceptors
const http = axios.create({
  baseURL: baseUrl, // baseUrl
  timeout: 5000 // The timeout period
  // More configuration items can be seen on the official website
})
http.interceptors.request.use(function () {... }) http.interceptors.response.use(function () {... })Copy the code

Encapsulation axios

// http.js
import axios from 'axios'
import { Loading, Toast } from 'vant';

export function fetch(url, params = {}, method = 'POST', { loading = true. config } = {}) {
  if(! url) {throw new Error('Url cannot be empty');
  }

  let isGet = method.toUpperCase() === 'GET',
    toast = null;

  if (loading) {
    toast = Toast.loading({
      duration: 0.mask: true.message: 'Loading... '
    });
  }

  return new Promise((resolve, reject) = > {
    axios({
      url: url,
      method,
      params: isGet ? params : ' '.data: isGet ? ' ': params, ... config }).then(rep= > {
      toast && toast.clear();
      resolve(rep);
    }, err= > {
      toast && toast.clear();
      reject(err);
    });
  });
}
Copy the code

reference

// api.js
import fetch from './http.js';
export const loginApi = params= > fetch('/login', {... params});/ / the Login module
// ...
import loginApi from '@/api.js'

methods: {
    onLogin() {
        loginApi({
            username: this.username,
            passward: this.passward
        }).then(res= >{
            console.log(res)
        })
    }
}
Copy the code

This is a simple package of AXIos. The configuration of AXIOS varies according to your needs. If you are interested, check out the documentation on the official website for more configuration information