In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to carry out axios source code reading and analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Overview
In the front-end development process, we often encounter situations where we need to send asynchronous requests. Using a fully functional and well-interfaced HTTP request library can greatly reduce our development costs and improve our development efficiency.
Axios is a very popular HTTP request library in recent years. At present, it has more than 40K star in GitHub and has been recommended by everyone.
Today, let's take a look at how axios is designed and what we can learn from it. When I was writing this article, the version of axios was 0.18.0. We will take this version of the code as an example to read and analyze the specific source code. Currently, all axios source files are in the lib folder, so the path we mentioned below refers to the path in the lib folder.
How to use axios
To understand the design of axios, we first need to look at how axios is used. Let's introduce the API of the following axios with a simple example.
Send a request
Axios ({method:'get', url:' http://bit.ly/2mTM3nY', responseType:'stream'}) .then (function (response) {response.data.pipe (fs.createWriteStream ('ada_lovelace.jpg'))})
This is an official example of API. As we can see from the above code, the use of axios is very similar to jQuery's ajax, both by returning a Promise (you can also use success's callback, but it is recommended to use Promise or await) to continue later operations.
This code example is simple, so I won't repeat it too much. Let's take a look at how to add a filter function.
Add interceptor (Interceptors) function
/ / add a request interceptor. Note that there are two functions, one processing succeeded and the other failed. The reason for this situation will be explained later: axios.interceptors.request.use (function (config) {/ / request pre-processing return config;}, function (error) {/ / request post-processing return Promise.reject (error);}) / / add a response interceptor axios.interceptors.response.use (function (response) {/ / process return response; for response data}, function (error) {/ / process return Promise.reject (error) after responding to errors;})
From the above example, we can know that we can perform data processing on the config parameters of the request before the request is sent, and we can also perform specific operations on the returned data after the request response. At the same time, we can handle specific errors when the request fails and the response fails.
Cancel HTTP request
When completing the search-related functions, we often need to send frequent requests for data query. Generally speaking, the next time a request is sent, we need to cancel the last request. Therefore, it is also an advantage to cancel the functions related to the request. The sample code for canceling a request by axios is as follows:
Const CancelToken = axios.CancelToken; const source = CancelToken.source (); axios.get ('/ user/12345', {cancelToken: source.token}) .catch (function (thrown) {if (axios.isCancel (thrown)) {console.log ('Request canceled', thrown.message);} else {/ / handle error}}) Axios.post ('/ user/12345', {name: 'new name'}, {cancelToken: source.token}) / / cancel the request (the message parameter is optional) source.cancel (' Operation canceled by the user.')
From the example above, we can see that axios uses a withdrawal proposal based on CancelToken. At present, however, the proposal has been withdrawn, and details can be found here. The specific implementation method of withdrawal will be explained in the later chapter when analyzing the source code.
How to design and implement the core module of axios
Through the above example, I believe you all have a general understanding of how to use axios. Next, we will analyze the design and implementation of axios according to the module. The following figure is the relevant axios files that we will cover in this blog. If readers are interested, you can read them through clone-related code combined with the blog, so as to deepen your understanding of the relevant modules.
HTTP request module
As the core module, the code related to the axios sending request is located in the core/dispatchReqeust.js file. Due to the limited space, I choose some of the key source codes for a brief introduction:
Module.exports = function dispatchRequest (config) {throwIfCancellationRequested (config); / / other source code / / default adapter is a module that can judge the current environment to choose whether to use Node or XHR to send requests var adapter = config.adapter | | defaults.adapter; return adapter (config) .then (function onAdapterResolution (response) {throwIfCancellationRequested (config); / / other source return response }, function onAdapterRejection (reason) {if (! isCancel (reason)) {throwIfCancellationRequested (config); / / other source code return Promise.reject (reason);});}
From the above code and example, we can know that the dispatchRequest method gets the module that sends the request by getting config.adapter, and we can also replace the native module by passing in an adapter function that conforms to the specification (although we don't usually do this, but it's a loosely coupled extension point).
In the default.js file, we can see the relevant adapter selection logic, that is, based on some properties and constructors unique to the current container.
Function getDefaultAdapter () {var adapter; / / only Node.js has a class if with variable type process (typeof process! = 'undefined' & & Object.prototype.toString.call (process) = =' [object process]') {/ / Node.js request module adapter = require ('. / adapters/http') } else if (typeof XMLHttpRequest! = = 'undefined') {/ / browser request module adapter = require ('. / adapters/xhr');} return adapter;}
Axios XHR module is relatively simple, for the encapsulation of XMLHTTPRequest objects, we will not introduce too much here, interested students can read by themselves, the code is located in the adapters/xhr.js file.
Interceptor module
Now that you understand the HTTP request sending module implemented by dispatchRequest, let's take a look at how axios handles request and response interceptor functions. Let's take a look at the requested uniform entry request function in axios.
Axios.prototype.request = function request (config) {/ / other code var chain = [dispatchRequest, undefined]; var promise = Promise.resolve (config); 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);}) While (chain.length) {promise = promise.then (chain.shift (), chain.shift ());} return promise;}
This function is the entry point for axios to send requests. Because the function implementation is relatively long, I will briefly talk about the relevant design ideas:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Chain is an execution queue. The initial value of this queue is a Promise with the config parameter.
In the chain execution queue, the initial function dispatchReqeust that sends the request and the corresponding undefined are inserted. You need to add a undefined later because in Promise, you need a success and a callback function for fail, as you can see from the code promise = promise.then (chain.shift (), chain.shift ());. So, dispatchReqeust and undefined, we can be a pair of functions.
In the chain execution queue, the function dispatchReqeust that sends the request is in the middle. It is preceded by a request interceptor, which is put in through the unshift method, and followed by a response interceptor, which is put in through push. Note that these functions are put in pairs, that is, two at a time.
From the request code above, we have a general idea of how to use the interceptor. Next, let's look at how to cancel a HTTP request.
Cancel request module
Cancel the request related module in the Cancel/ folder. Let's take a look at the relevant key codes.
First, let's look at the metadata Cancel class. It is used to record cancellation status of a class, the specific code is as follows:
Function Cancel (message) {this.message = message;} Cancel.prototype.toString = function toString () {return 'Cancel' + (this.message?':'+ this.message:');}; Cancel.prototype.__CANCEL__ = true
In the CancelToken class, it implements the cancellation of the HTTP request by passing a Promise method, so let's take a look at the specific code:
Function CancelToken (executor) {if (typeof executor! = = 'function') {throw new TypeError (' executor must be a function.');} var resolvePromise; this.promise = new Promise (function promiseExecutor (resolve) {resolvePromise = resolve;}); var token = this Executor (function cancel (message) {if (token.reason) {/ / Cancellation has already been requested return;} token.reason = new Cancel (message); resolvePromise (token.reason);});} CancelToken.source = function source () {var cancel; var token = new CancelToken (function executor (c) {cancel = c) }); return {token: token, cancel: cancel};}
In the adapter/xhr.js file, there is a corresponding code to cancel the request:
If (config.cancelToken) {/ / waiting for config.cancelToken.promise.then to be cancelled (function onCanceled (cancel) {if (! request) {return;} request.abort (); reject (cancel); / / reset request request = null;});}
Combined with the above example of canceling a HTTP request and this code, let's briefly talk about the relevant implementation logic:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
In requests that may need to be cancelled, we call the source method during initialization, which returns an instance of the CancelToken class An and a function cancel.
In instance A returned by the source method, a promise in the pending state is initialized. After we pass the entire instance A to axios, this promise is used as a trigger to cancel the request.
When the cancel method returned by the source method is called, the promise state in instance A changes from pending to fulfilled, immediately triggering the callback function of then, which triggers the cancellation logic of axios-- request.abort ().
What can I learn from the design of axios?
Send the processing logic of the request function
As mentioned in the previous chapter, when axios handles the dispatchRequest function of sending a request, it is not treated as a special function, but is treated equally and placed in the middle of the queue, thus ensuring the consistency of queue processing and improving the readability of the code.
Processing Logic of Adapter
In the processing logic of adapter, axios does not use http and xhr modules (one for Node.js to send requests and the other for browsers to send requests) as its own modules to drink directly in dispatchRequest. Instead, it is introduced by default in the default.js file through configuration. This not only ensures the low coupling between the two modules, but also reserves room for users to need a custom request sending module in the future.
Cancel the processing logic of the HTTP request
In the logic of canceling the HTTP request, axios cleverly uses a Promise as a trigger to pass the resolve function to the outside in the form of parameters in the callback. This can not only ensure the coherence of the internal logic, but also ensure that when you need to cancel the request, you do not need to change the sample data of the related class directly, and avoid invading other modules to a certain extent.
In this paper, the use, design ideas and implementation methods of axios are introduced in detail. Through the above article, readers can understand the design ideas of axios, and at the same time, they can learn about module encapsulation and interaction in axios code.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.