Basic usage of axios

1. Download axios

  • yarn add axios -S
  • npm i axios -S

2. Encapsulate the request tool

  • SRC file to create utils/request.js
import axios from 'axios'
const request = axios.create({
    baseURL: 'Uniform prefix address for interfaces'
})
export default ({ method = 'GET', url, params, data, headers }) => {
    return request({ method, url, params, data, headers })
}
Copy the code

In the future library change, only need to change here, the logical page does not move, to ensure the reuse and independence of code (high cohesion and low coupling)

3. Encapsulate interface tools

  • SRC file to create API/various interface function files
    import $http from '@/utils/request.js'
    const customFn = ( data, params, headers ) = > { // Parameters are passed as needed
        return $http({
            method: 'Default is GET'.url: 'Requested address',
            data,params,headers,// Receive on demand})}export { customFn } // Export as needed
Copy the code

4. Project application

  • Import interface function files as required
  • Call the function to send the request
    import { customFn } from '@/ API/interface function file '
    async function Fn( data, params, headers ) { // Parameters are passed as needed
        try {
            const { data:res } = await customFn( data, params, headers ) // Receive on demand
            console.log(res)
        } catch(error) {
            console.log(error)
        }
    }
Copy the code

Async and await can only receive the return value of the success state. Together with try-catch, async and await can receive the return value of the failed state

Axios interceptor

1. Request interceptor

    // Add request interceptor
    axios.interceptors.request.use(function (config) {
      return config // The data at the time of sending the request
    }, function (error) {
      // What to do about the request error
      return Promise.reject(error)
    })
Copy the code

2. Response interceptor

    // Add a response interceptor
    axios.interceptors.response.use(function (response) { // Enter if the status code starts with 2xx/3xx
        // What to do with the response data
        return response
    }, function (error) { // Response status code 4xx/5xx enter here
        return Promise.reject(error)
    })
Copy the code

3. Remove interceptors

    const myInterceptors = axios.interceptors.response.use(...)
    axios.interceptors.response.eject(myInterceptors)
Copy the code