directory

  1. introduce
  2. Initialization: AXIos, axios, intance
  3. Overall process: Request => deispatchRequest => Adapter
  4. Data conversion: despatchRequest
  5. Adapter: Adapter
  6. Interceptor: Request => deispatchRequest => Response
  7. Cancel request: cancelToken => Adapter => Cancel
  8. review

introduce

Features:

  1. Supports browsers and Node.js
  2. API promise
  3. Request/response interceptor
  4. Request/response formatting methods
  5. 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:

  1. The Axios constructor generates objects with defaults and interceptor properties
  2. Bind (request, content) returns the request method of a closure.
  3. Copy Axios. Prototype (get/post/request)
  4. Copy the Defaults and interceptor properties on the context.

Line by line analysis + debugger:

  1. The Axios constructor generates objects with defaults and interceptor properties
  2. 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

  1. Copy Axios. Prototype (get/post/request)
utils.extend(instance, Axios.prototype, context);
Copy the code

  1. 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

  1. Syntax: Axios is not an object instance of Axios
  2. Functionally: Axios has all the functionality of an AXIos instance (method: axios.porotype, attribute: defaults/interceptors)
  3. 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:

  1. Request: Request interception => despatchRequest => response interception through promise
  2. DespatchRequest: Request data conversion => Adapter => response data conversion
  3. 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

  1. The difference between AXIos and AXIos, and the initialization process
  2. Config responsibility chain, responsibilities of key modules request, despatchRequest and ADPter, and overall request process.
  3. The default conversion of despatchRequest is automatically converted to JSON
  4. Adapter implementation
  5. Request interceptor implementation, cancel interceptor, execution order.
  6. 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