Sometimes we need to process the requests sent by Axios uniformly. Here we need to use interceptors
- First, create an Axios example
import axios from 'axios' const $http = axios.create({ baseURL: '/api/', timeout: 5000 // request timeout })
- Request interceptor, inBefore the request is initiatedInterception processing
//HTTP response interceptor $http.interceptors.response.use( config => { //Intercept the request and do unified processing console.log ('data to be requested '); console.log(config); return config }, error => { return Promise.reject(error) })
- Response interceptor, after the interface returns dataBefore response processingInterception processing
//HTTP response interceptor $http.interceptors.response.use( response => { //Intercept response and do unified processing console.log ('data request succeeded '); console.log(response); const res = response.data return res }, //Interface error state handling, that is, handling when there is no response error => { return Promise.reject ( error.response.status )// returns the error information returned by the interface })
- After that, you can expose the Axios example and use it normally
export default $http
This work adoptsCC agreementReprint must indicate the author and the link of this article