问题:平时我们发送axios请求可能会有请求拦截或者响应拦截,但是我们axios请求拦截和响应拦截的执行顺是不一致的。

axios拦截器的执行顺序

1.请求拦截:axios的请求拦截会先执行最后指定的回调函数先执行,依次向前面执行。
2.响应拦截:axios的响应拦截会先执行最先指定的回调函数先执行,依次向后面执行
以下列代码为例

axios.interceptors.request.use(config => {
            console.log(`请求拦截1`);
            return config;
        });
        axios.interceptors.request.use(config => {
            // 在发送请求之前做些什么
            console.log(`请求拦截2`);
            return config;
        });
 
        // 添加响应拦截器
        axios.interceptors.response.use(response => {
            // 对响应数据做点什么
            console.log(`成功的响应拦截1`);
            return response.data;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(response => {
            // 对响应数据做点什么
            console.log(`成功的响应拦截2`);
            return response;
       });
        
        // 发送请求
        axios.get('/posts')
            .then(response => {
                console.log('成功了');
            })

以上代码的打印结果顺序为:
1.console.log(请求拦截2);
2.console.log(请求拦截1);
3.console.log(成功的响应拦截1);
4.console.log(成功的响应拦截2);
5.console.log(成功了);

为什么请求拦截2会在请求拦截1前面执行呢?
因为axios将响应拦截和请求拦截都存放在一个数组中

/*创建用于保存请求/响应拦截函数的数组
数组的中间放发送请求的函数
数组的左边放请求拦截器函数(成功/失败)
数组的右边放响应拦截器函数*/
var chain = [dispatchRequest,undefined];
//后添加的请求拦截器保存在数组的前面
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled,interceptor.rejected);
});
//后添加的响应拦截器保存在数组的后面
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled,interceptor.rejected);
});

而axios开始发送请求,是每次从数组中删除两个回调函数来开始执行,只到数组为空则执行完成。

//通过promise的then()串连起所有的请求拦截器/请求方法/响应拦截器
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}

axios的请求拦截是向数组前面追加的,而响应拦截是向数组后面追加的,所以当axios发送请求时,

请求拦截的回调函数最后指定的,最先被调用,从左向右执行。如下图所示:

axios响应拦截器 获取错误信息 axios请求响应拦截_前端


以上就是axios发送请求关于请求拦截和响应拦截的执行过程,觉得有用的话点个赞吧!