Home >Web Front-end >JS Tutorial >An in-depth analysis of the process and principles of asynchronous requests in axios
axios is a Promise-based method that can send get, post and other requests, and can be used by both front and back ends. [Recommended: Ajax video tutorial, web front-end]
axios library is exposed to the outside world An axios instance is mounted, and an Axios method is mounted in the axios instance. The Axios method has an interceptors object
(interceptor), and the interceptors object
has a request object
and response object
, and request object
and response object
both have use methods, so we can call axios.interceptors.request.use() and axios.interceptors .response.use().
##interceptors objectThe
request object and
response object are actually a use To manage the array of interceptors (handlers). When we call axios.interceptors.request.use(), a success callback and a failure callback will be pushed in the request's interceptor array (handlers). Each time it is used, it is pushed once, similar to [res1, rej1, res2, rej2...]
It is an array that stores all callbacks, Because it is used for Promise, it needs to use two values , the initial values are dispatchRequest and undefiend. Next, Promise.resolve(config).then(fn1, fn2). When the result in config is fulfilled (successful), the configuration in config is passed to fn1 and executed. If it is reject (error report), the error result is passed to fn2 and executed. That is, Promise.resolve(config).then(chain[0], chain[1]). chain[0] is a success callback, chain[1] is a failure callback. There are many configuration items in config, they may be a string value or method, etc.
request array to the front of the
chain array, and move ## The callback function in #response array
is pushed to the end of chain array
. The final chain array
is similar to [res2, rej2, res1, rej1, dispatchRequest, undefiend, res3, rej3, res4, rej4].
is used to execute axios.request
, dispatchRequest method
has an adapter
, it will call different objects according to different environments. If it is in a browser environment, call the XMLHttpRequest object
. If it is a nodejs environment, call http object
. That's why it can be used on both the front-end and the back-end. adapter
will parse and encapsulate the requested data, and the encapsulated object is the response response object
we can see.
, the callback function of interceptors.response
will be executed. This is why the execution order we see is that the latter's interceptors.request
is executed before the former's interceptors.requets
, and then axios.request
, Finally, execute interceptors.response
.
Common methods: get, post, request
axios.get
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });axios.post
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
can be passed in Many request configurations
axios.request({ url: '/user', method: 'get', // 默认 baseURL: '/api', //...})2. Pass in the configuration method
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'})
.then(function (response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
4. Response module
{ data: {}, status: 200, statusText: 'ok', header: {}, config: {}, request: {}}
5. Configuration
1. Global axios configurationaxios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const instance = axios.create({
baseURL: 'https://api.example.com'});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
const instance = axios.create();instance.defaults.timeout = 2500;instance.get('/longRequest', {
timeout: 5000});
The final timeout setting time is 5000, so the priority here is the configuration in the request>instantiation configuration>axios default configuration
6. Interceptors
axios.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use(function (response) { return response; }, function (error) { return Promise.reject(error); });
7. Concurrent request processing
// 把axios请求放进函数里function getUserAccount() { return axios.get('/user/12345');} function getUserPermissions() { return axios.get('/user/12345/permissions');}//函数执行放到Promise里面排队,挨个响应。Promise.all([getUserAccount(), getUserPermissions()]) .then(function (results) { const acct = results[0]; const perm = results[1]; });
The above is the detailed content of An in-depth analysis of the process and principles of asynchronous requests in axios. For more information, please follow other related articles on the PHP Chinese website!