The concept of interceptors
Is actually do you want to intercept live our process of this request, for example, if you want to do something before the request, intercepting the request, such as finish in and ask for it, or is to do the request, and then return the data, can intercept and back after processing, the process of vernacular some explanation is so so, I most afraid to hear some very profound conceptual explanation, Here output does not say so many professional terms!
Axios offers four ways to intercept:
- Axios has a global interception method:
axios.interceptors()
- After the interception is successful, the data must return. Otherwise, the data cannot be obtained
Interception on successful and failed requests
// instance Intercepts the request
instance.interceptors.request.use(
config= > {
console.log(config);
// Intercept and process the information here
return config;
}, err= > {
console.log(err);
})
Copy the code
Usage scenario:
- For example, some information in config does not meet the server requirements, you can handle it here, or add a custom headers
- For example, every time you send a network request, you want to display a request icon in the interface. It is displayed when the request is made and hidden after success
- For example, certain network requests (such as login must carry (token)) must carry some special information
Intercept on response success and response failure
For example, if only one data is returned after intercepting the response, the other data will be filtered out, and the final response data obtained by the request will only be data!
// Intercept the response
instance.interceptors.response.use(
res= > {
console.log(res)
return res.data
}, err= > {
console.log(err)
}
)
Copy the code
A complete encapsulating example of Axios:
Simply save this to a request.js file and call it elsewhere to request the interface data
import axios from 'axios'
// The default export is used for future extension. Multiple methods can be exported
export function request(config){
// 1. Create the Axios instance
const instance = axios.create({
baseURL: 'https://store.crmeb.net/api/pc'.timeout: 5000
})
// Intercept the request
instance.interceptors.request.use(
config= > {
console.log(config);
return config;
}, err= > {
console.log(err);
})
// Intercept the response
instance.interceptors.response.use(
res= > {
console.log(res)
return res.data
}, err= > {
console.log(err)
}
)
// Send the request
return instance(config)
}
Copy the code
Method of use
import { request } from "./network/request"
request({
url: '/get_company_info',
}).then(res= > {
console.log(res)
}).catch(err= > {
console.log(err)
})
Copy the code