Axios has been so popular since its inception that it now covers most of the front end. So Axios has to have it all. I recently combed through some axios knowledge points that may not be familiar to developers, so that we can make progress together.

Axios global configuration

  1. Request the address

You can directly set the interface domain name when you need to configure a single or limited interface domain name. You need to manually change the interface domain name when switching between the production environment and development environment

axios.defaults.baseURL="http://location:9999/api";
Copy the code
  1. Timeout setting (1000=1s)
axios.defaults.timeout = 1000
Copy the code

2. Interceptor

Axios offers two broad categories of interceptors. One is request-direction interception (success or failure) and the other is response-direction interception (success or failure)Copy the code
Functions of interceptor: It is mainly used to initiate a request in network request or process the corresponding operation in network request. Animation of webpage loading can be added when initiating a request, and corresponding data processing can be carried out when the token is authenticated and the login response is forcedCopy the code

Request direction interceptor

    
axios.interceptors.request.use(config= > {
    console.log("Enter request interceptor");
    console.log(config);
    // Interceptor cleared
    return config
}, err => {
    console.log("Request failed");
    console.log(err);
})

axios.get("https://s.search.bilibili.com/main/hotword?mid=&buvid=233C35D5-EFCF-429B-8461-983C2A05C99940777infoc").then(res= > {
    console.log(res);
})

Copy the code

Response direction interceptor

    
axios.interceptors.response.use(config= > {
    console.log("Enter response interceptor.");
    return config.data / / release
}, err => {
    console.log("Response direction failed");
    console.log(err);
})

axios.get("https://s.search.bilibili.com/main/hotword?mid=&buvid=233C35D5-EFCF-429B-8461-983C2A05C99940777infoc").then(res= > {
    console.log(res);
})

Copy the code

Before interceptor release we can operate or the animation loaded by the web page, authentication token forcible login

Module encapsulation of AXIos in VUE

First type of encapsulation


// Create a new directory and file./network/request.js
import axios from 'axios'

export function request(config){
    axios.defaults.baseURL = 'http://localhost:9999/api'
    axios(config.url)
    .then(res= >{
        config.success(res);
    }).cath(err= >{ config.fail(err); })}// Caller location
import {request} from './network/request.js'

request({
    url:'getInfo'.success:res= >{
        console.log(res)
    },
    fail:err= >{
        console.log(err)
    }
})

Copy the code

The second encapsulation is based on promises


// Create a new directory and file./network/request.js
import axios from 'axios'

export function request(config){
    let newVar = axios.create({
        baseURL:"http://http://localhost:9999/api".timeout:5000
    })
    return newVal(config);
}

/ / the caller
import {request} from './network/request.js'

request({
    url:'getInfo'
}).then(res= >{
    console.log(res)
})


Copy the code

Third type of encapsulation (detailed)

// Create a new directory and file./network/request.js
import axios from 'axios'
let baseURL = 'http://http://localhost:9999/api'

export const getRequest = (params) = > {
  return axios({
    method: 'get'.url: `${baseURL}`.params: params
  })
}
export const postRequest = (params) = > {
  return axios({
    method: 'post'.url: `${baseURL}`.data: params,
    transformRequest: [function (data) {
      let ret = ' '
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }]
  })
}

export const getDoc = (params) = > {
  let token = Cookies.get('token')
  let paramsObj = {
    'token': token,
    'method': 'doc'.'params': params
  }
  return getRequest({
    'request': JSON.stringify(paramsObj)
  })
}

/ / the caller
import {getDoc} from './network/request.js'

getDoc({
  // Enter parameters
  "id":1."subject": "Chinese"."orders": "1"// This parameter is optional. 0 indicates the sequence, and 1 indicates the reverse sequence
}).then(res= > {
    console.log(res)
})
Copy the code

The last

The HTTP library is easy to use, concise, and efficient, and we use it a lot, but there are some details that we don’t notice, and knowing these details can help us write better code. If where have wrong place hope message correct, progress together!