directory
- introduce
- Initialization: AXIos, axios, intance
- Overall process: Request => deispatchRequest => Adapter
- Data conversion: despatchRequest
- Adapter: Adapter
- Interceptor: Request => deispatchRequest => Response
- Cancel request: cancelToken => Adapter => Cancel
- review
introduce
Features:
- Supports browsers and Node.js
- API promise
- Request/response interceptor
- Request/response formatting methods
- Cancel the request
Usage:
// Send the request directly
axios(config)
axios(url[, config])
axios.request(config)
// Alias methodaxios.get(url[, config]) axios.delete(url[, config]) axios.post(url[, data, config]) axios.put(url[, data, Config]) axios. Defaults. XXX: the default global configuration request axios. Interceptors. Request. Use () : add request interceptor axios. Interceptors. Response. Use () : Add response interceptor axios.create([config]): Creates a new AXIos// Only the default axios method exists, the newly created one does notCancelToken(): Token object used to create the cancellation request axios.iscancel (): Axios.all (Promises): Promises for batch execution of multiple asynchronous requests Axios.spread ():Copy the code
The directory structure
├ ─ ─ adapters │ ├ ─ ─ the README. Md │ ├ ─ ─ HTTP. Js / / Node environment request │ └ ─ ─ XHR. Js / / browser environment request ├ ─ ─ axios. Js file / / entry Initialize ├ ─ ─ the cancel / / Request Cancel module │ ├ ─ ─ the Cancel. Js │ ├ ─ ─ CancelToken. Js │ └ ─ ─ isCancel. Js ├ ─ ─ the core / / core modules │ ├ ─ ─ Axios. Js / / initialization │ ├ ─ ─ │ ├─ buildFullPath.js │ ├─ createError. Js │ ├─ dispatchRequest.js // Request to call │ ├─ EnhanceError. Js │ ├ ─ ─ mergeConfig. Js │ ├ ─ ─ settle. Js │ └ ─ ─ transformData. Js / / data conversion ├ ─ ─ defaults. Js / / the default configuration ├ ─ ─ env │ ├ ─ ─ the README. Md │ └ ─ ─ data. Js ├ ─ ─ helpers │ ├ ─ ─ the README. Md │ ├ ─ ─ the bind. Js / / bind │ ├ ─ ─ buildURL. Js │ ├ ─ ─ combineURLs. Js │ ├── Cookies. Js │ ├── Heavy Metal Flag. Js │ ├─ Heavy metal Flag ── Heavy metal Flag ├─ ├─ ├─ ├─ ├.js // Type determination, object methods (forEach, Merge, extend)Copy the code
Initialize the
Starting with this question axios to Axios, right?Entry file lib/axios.js, throughThe factory function createInstance is initialized, get axios, and mount the Cancel, CancelToken, and other methods to Axios.
The initialization process starts with the factory function createInstance:
- The Axios constructor generates objects with defaults and interceptor properties
- Bind (request, content) returns the request method of a closure.
- Copy Axios. Prototype (get/post/request)
- Copy the Defaults and interceptor properties on the context.
Line by line analysis + debugger:
- The Axios constructor generates objects with defaults and interceptor properties
- Bind (request, content) returns the request method of a closure.
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
Copy the code
- Copy Axios. Prototype (get/post/request)
utils.extend(instance, Axios.prototype, context);
Copy the code
- Copy the Defaults and interceptor properties on the context.
The Axios constructor: delete, get, and other methods are aliases of Request, which combine different config configurations.
Axios versus Axios
- Syntax: Axios is not an object instance of Axios
- Functionally: Axios has all the functionality of an AXIos instance (method: axios.porotype, attribute: defaults/interceptors)
- Axios is the warp function returned by the axios.porotype. request function bind and can be used directly.
Axios.created Differentiates the created object from axios
Same: sends requests directly, has request, get/ POST methods, and has defaults/interceptors attributes. Different: The new instance does not have the Cancel, CancelToken methods.
15
The whole process
Chain of Responsibility model
Behavioral patterns are responsible for effective communication and delegation of responsibilities between objects.
The chain of responsibility pattern is a behavior design pattern that allows you to send requests down a chain of handlers. Upon receipt of the request, each handler can either process it or pass it on to the next handler on the chain.
Axios.porotype.request(config) ==> despatchRequest(config) ==> Adapter (config)
Important modules and responsibilities:
- Request: Request interception => despatchRequest => response interception through promise
- DespatchRequest: Request data conversion => Adapter => response data conversion
- Adpter: The request function returns a promise based on the context
Overall process:
Convert data despatchRequest
The default conversion
The adapter
The structural pattern describes how to assemble objects and classes into a larger structure while keeping the structure flexible and efficient.
The adapter pattern is a structural design pattern that enables objects with incompatible interfaces to cooperate.
The interceptor
Interceptor management
Cancel the interceptor? Interceptor execution order?
lib/core/InterceptorManager.js
- User:
- Eject: delete
- ForEach: gets all
Add/remove interceptors
lib/core/Axios.js Axios.prototype.request
Asynchronous execution
Synchronous execution
Execution order
Write a demo
const config = {a:'111'}
const promise = Promise.resolve(config);
const arr = [promise]
let resault = promise
arr.push((config) => {
config['user1'] = 111
console.log(config, '111')
return config
})
arr.push((config) => {
config['user2'] = 2222
console.log(config, '222')
return config
})
arr.push((config) => {
config['user3'] = 3333
console.log(config, '333')
return config
})
while (arr.length) {
resault = promise.then(arr.shift())
}
Copy the code
Cancel the request
Cancelled use
lib/cancel/CancelToken.js The main function and subscribe
Subscribe to the function
CancelToken = new axios.CancelToken(c => cancel = c)
The second step in XHR canceltoken. subscribe stores the cancellation event
The third step executes the cancellation event stored via SUBSCRIBE
Observer model
The Observer pattern is a behavior design pattern that allows you to define a subscription mechanism that notifies multiple other objects that “observe” an object when an event occurs.
Discussion on the relationship between observer pattern and publish subscription?The Observer pattern contains publish subscriptions. Publish subscribe is an upgraded variant of the Observer. The difference between the observer mode and the publish/subscribe mode is whether there is an event dispatch center.
review
- The difference between AXIos and AXIos, and the initialization process
- Config responsibility chain, responsibilities of key modules request, despatchRequest and ADPter, and overall request process.
- The default conversion of despatchRequest is automatically converted to JSON
- Adapter implementation
- Request interceptor implementation, cancel interceptor, execution order.
- Cancel the implementation of the request
Comprehension:
- Clear responsibilities of modules
- Adaptor easy to expand
- Interceptors, flexible format conversion
- Classification of design patterns: creation, structure, and behavior
- Tips & Methods & Keep learning