axios Request interceptor , That is, execute the custom function before the request is sent .

axios Source version - ^0.27.2 ( The source code is a simplified version )

In business, we usually write request interceptors like this , The code is as follows :

//  Create a new instance 
var service = axios.create(); // Request interceptor
service.interceptors.request.use((config) => {
// Ask for the head to add token
config.headers['token'] = 'xxx';
... ... ... return config;
}, (err) => {
return Promise.reject(err);

among service.interceptors.request.use The method worked , Its core source code is as follows :

/* axios/core/Axios.js */
// Axios Constructors
function Axios(defaultConfig) {
this.defaults = defaultConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
} /* axios/core/InterceptorManager.js */
// InterceptorManager Constructors
function InterceptorManager() {
// Default empty array
this.handlers= [];
} // InterceptorManager It's a prototype use Method ( In the above business use Method , In fact, this method is called )
InterceptorManager.prototype.use = function(fulfilled, rejected) {
// Array push A callback containing a successful callback 、 Failed callback object
fulfilled: fulfilled,
rejected: rejected
}); // Return array length - 1
return this.handlers.length - 1;
} // InterceptorManager It's a prototype eject Method
InterceptorManager.prototype.eject = function(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
} // InterceptorManager It's a prototype forEach Method
InterceptorManager.prototype.forEach = function(fn) {
utils.forEach(this.handlers, function(h) {
if (h !== null) {

service.interceptors.request.use It turned out to be to handlers Array push An object , Printable information viewing , The code is as follows :

// give the result as follows
fulfilled: (config) => {...},
rejedcted: (err) => {...}

that , When sending a request , How the request interceptor works , The code is as follows :

Axios.prototype.request = function(defaultConfigOrUrl, config) {
... ... ... var requestInterceptorChain = [];
this.interceptors.request.forEach(function (interceptor) {
// The of this instance will be this.this.interceptors.request.handlers Put in requestChain
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
}); var promise; // dispatchRequest Is the request process
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain); promise = Promise.resolve(config);
while (chain.length) {
// call chaining , Keep reducing chain Length of array , Until empty
promise = promise.then(chain.shift(), chain.shift());
} return promise; ... ... ...

That's why axios Is based on promise Of , Request interceptor --> request --> Response interceptors .

Cancel the interceptor

Cancel the interceptor function , The author thinks it has little effect , The code is as follows :

var requestNumber = service.interceptors.request.use(fulfilled, rejected);

//  Cancel request interceptor 

Multiple request interceptors

It mainly talks about the execution sequence of multiple request interceptors , The code is as follows :

//  The first request interceptor 
service.interceptors.request.use(fulfilled1, rejected1); // The second request interceptor
service.interceptors.request.use(fulfilled2, rejected2); // The third request interceptor
service.interceptors.request.use(fulfilled3, rejected3); // Based on the above Axios.prototype.request Method , You can know handlers Array :[fulfilled3, rejected3, fulfilled2, rejected2, fulfilled1, rejected1] // So the execution sequence :fulfilled3 --> fulfilled2 --> fulfilled1

axios The source code parsing - More articles on request interceptors

  1. axios The source code parsing ( Next ) A detailed explanation of the interceptor

    axios In addition to initializing the configuration , Other useful should be interceptors , Interceptors are divided into request interceptors and response interceptors : Request interceptor     ; Do something before the request is sent , For example, add... To each request body token, Unified treatment, if you want to ...

  2. Okhttp3 The source code parsing (5)- Interceptor RetryAndFollowUpInterceptor

    ### Preface review : [Okhttp The basic usage of ]( [Okhttp3 The source code parsing (1)-OkHttpClient analysis ](htt ...

  3. Okhttp3 The source code parsing (4)- Interceptors and design patterns

    ### Preface review : [Okhttp The basic usage of ]( [Okhttp3 The source code parsing (1)-OkHttpClient analysis ](htt ...

  4. The source code parsing Grpc Interceptor (C# edition )

    Preface Actually Grpc Interceptors are something I've studied before , But I see online related C# Version of the source code analysis is relatively less , So I borrow this article to share with you Grpc The implementation of interceptors , I don't say much nonsense , Speak directly (Grpc The source code looks very convenient , Packages can be restored automatically ...

  5. springMVC Interceptor of source code analysis

    One thing has been used for a long time , Nature will rise from the level of using only to the level of exploring its principles , stay javaweb in springmvc Even more so , The better the framework , The underlying implementation code is more complex , As far as I'm concerned , An excellent programming ape is equivalent to a Wulin master , constantly ...

  6. springMVC Source code analysis --HandlerInterceptor Interceptor calls procedure ( Two )

    In the last blog springMVC Source code analysis --HandlerInterceptor Interceptor ( One ) We introduced HandlerInterceptor Interceptor related content , I learned that HandlerInterceptor ...

  7. axios The source code parsing ( in ) The code structure

    axios Now the latest version is v0.19.0, In this section, we will analyze the source code of its implementation , First, through gitHub Address to get its source code , Address : ...

  8. Struts 2.3.24 The source code parsing +Struts2 Intercept parameters , Processing requests , Go back to the foreground and analyze the process in detail

    Struts2 Official website : The latest version :Struts 2.3.24 Struts1 It has been completely eliminated , and Struts2 It's for reference webwork Design according to the design concept of ...

  9. SpringMVC Source code reading : Interceptor

    1. Preface SpringMVC Is currently the J2EE Mainstream of the platform Web frame , Unfamiliar garden friends can see SpringMVC Introduction to source code reading , It narrates the SpringMVC Basic knowledge and source code reading skills This article will be through the source code ( be based on Spring ...

  10. springMVC Source code analysis --HandlerInterceptor Interceptor ( One )

    Yes SpringMVC Someone who knows something must have been in contact with HandlerInterceptor Interceptor ,HandlerInterceptor The interface provides us with 3 A way : (1)preHandle: In execution controll ...

Random recommendation

  1. XSS Front end firewall —— Suspicious module interception

    The system introduced in the previous article , Has been able to warn most of the real world XSS attack , But it's easy to get around . Because it is in the front-end protection , Policy configuration can be found in the source code , So we can try out a solution soon . And the attacker can mask the log interface , Never send... On your computer ...

  2. sketch MVC Frame mode and in you (Android) Application in the project

    The title is the question of Ali's telephone interview , I always thought I knew MVC Pattern , When asked , I can't put MVC and Android Each component in the , therefore , The interview must be over , But interviews are also a way to learn , You can see what big companies like , And from ...

  3. [HDOJ5543]Pick The Sticks(DP,01 knapsack )

    Topic link : The question : Xiang Changwei L Cover the line segment on the line segment , requirement : Or these segments are all in L On the line segment of , Or there is no more than half its length ...

  4. alert rapidxml The trap of : When adding nodes , Please guarantee the life cycle of the variable Use... In projects xml pack . Parsing protocols ,HQ Specified the use of rapidxml-- Claims to be the fastest xml Parser . It's very functional ...

  5. java How the code is generated chm

    Because we need to make a frame into chm, I found several articles on the Internet today Li Shunli First step , from eclip ...

  6. ububru Next redmine Installation tutorial

    1. Make sure you have installed it before you install it mysql 2. Connect mysql Create database mysql -u root –p CREATE DATABASE redmine CHARACTER SET utf8; CRE ...

  7. hive Function learning

    NAME PRICE ---- ----- AAA 1.59 AAA 2.00 AAA 0.75 BBB 3.48 BBB 2.19 BBB 0.99 BBB 2.50 I would like to ...

  8. QMessageBox usage

    Case a :QMessageBox msgBox;msgBox.setText("The document has been modified.");msgBox.setInforma ...

  9. ABP+AdminLTE+Bootstrap Table Section 3 of the authority management system --abp Hierarchical system and entity related

    Said so long , I haven't talked about it in detail yet abp frame ,abp It's based on DDD( Domain-driven design ) A closer look at the principles is as follows : Let's look at our project solutions as follows : JCmsErp.Application, application layer : Coordination between presentation layer and domain layer ...

  10. Arrangement Cocos2d-x Interview questions

    I listened to Tencent yesterday 2015 Online publicity meeting of school recruitment , I saw a lot of game technology Steven, He summed up the need for talent to love technology , Can hold on , Picky enough . It's time for school recruitment , Come on! , Sao Nian ~ About online cocos2d-x There are few interview questions , Here we collect and sort out ...