In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to realize the request for retry in Axios". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
I. the scheme of interceptor to realize the request for retry
Axios is a Promise-based HTTP client, while the HTTP protocol is based on requests and responses:
So Axios provides a request interceptor and a response interceptor to handle the request and response respectively, and their functions are as follows:
Request interceptor: the function of this interceptor is to uniformly perform certain operations before the request is sent, such as adding a token field to the request header.
Response interceptor: the function of this kind of interceptor is to perform some operations uniformly after receiving the response from the server, such as automatically jumping to the login page when the response status code is 401.
It is easy to set the interceptor in Axios. Through the use method provided by the axios.interceptors.request and axios.interceptors.response objects, you can set the request interceptor and the response interceptor respectively:
Export interface AxiosInstance {interceptors: {request: AxiosInterceptorManager; response: AxiosInterceptorManager;};} export interface AxiosInterceptorManager {use (onFulfilled?: (value: v) = > V | Promise, onRejected?: (error: any) = > any): number; eject (id: number): void;}
For the ability to request a retry, we want to enable the user to set not only the number of retries, but also the retry delay. When the request fails, if the configuration object of the request is configured with the number of retries, Axios will reinitiate the request to retry the operation. In order to make the request retry globally, let's implement the request retry function on the response interceptor. The specific code is as follows:
Axios.interceptors.response.use (null, (err) = > {let config = err.config; if (! config | |! config.retryTimes) return Promise.reject (err); const {_ _ retryCount = 0, retryDelay = 300, retryTimes} = config; / / set the number of retries on the request object config.__retryCount = _ _ retryCount; / / to determine whether the number of retries if (_ retryCount > = retryTimes) {return Promise.reject (err) is exceeded } / / increase the number of retries config.__retryCount++; / / delay processing const delay = new Promise ((resolve) = > {setTimeout () = > {resolve ();}, retryDelay);}); / / re-initiate the request return delay.then (function () {return axios (config);});})
The above code is not complicated, and the corresponding processing flow is shown in the following figure:
After introducing how to use interceptor to implement the function of request retry, let's introduce the solution of adapter to implement request retry.
Second, the adapter realizes the scheme of requesting retry.
Axios introduces adapters so that it can support both browser and Node.js environments. For browser environments, it sends HTTP requests by encapsulating XMLHttpRequest API, while for Node.js environments, it sends HTTP requests by encapsulating Node.js 's built-in http and https modules.
How do I cache request data in Axios? In this article, Brother Po shows how to cache requested data by enhancing the default Axios adapter. Similarly, with a similar line of thinking, we can implement the ability to request a retry by enhancing the default Axios adapter.
Before we show you how to enhance the default adapter, let's take a look at Axios's built-in xhrAdapter adapter, which is defined in the lib/adapters/xhr.js file:
/ / lib/adapters/xhr.js module.exports = function xhrAdapter (config) {return new Promise (function dispatchXhrRequest (resolve, reject) {var requestData = config.data; var requestHeaders = config.headers; var request = new XMLHttpRequest (); / / omit most of the code var fullPath = buildFullPath (config.baseURL, config.url); request.open (config.method.toUpperCase (), buildURL (fullPath, config.params, config.paramsSerializer), true) / / Set the request timeout in MS request.timeout = config.timeout; / / Listen for readystate request.onreadystatechange = function handleLoad () {.} / / Send the request request.send (requestData);});}
Obviously the xhrAdapter adapter is a function object that takes a config parameter and returns a Promise object. Inside the xhrAdapter adapter, the XMLHttpRequest API is eventually used to send the HTTP request. In order to implement the function of requesting a retry, we can consider using higher-order functions to enhance the functionality of the xhrAdapter adapter.
2.1Defining retryAdapterEnhancer function
To give users more flexible control over the ability to request a retry, we define a retryAdapterEnhancer function that supports two parameters:
Adapter: pre-enhanced Axios adapter object
Options: cache configuration object, which supports two attributes, which are used to configure different functions:
Times: globally sets the number of retries requested
Delay: globally sets the delay time of the request in ms.
After understanding the parameters of the retryAdapterEnhancer function, let's take a look at the implementation of the function:
Function retryAdapterEnhancer (adapter, options) {const {times = 0, delay = 300} = options; return async (config) = > {const {retryTimes = times, retryDelay = delay} = config; let _ _ retryCount = 0; const request = async () = > {try {return await adapter (config) } catch (err) {/ / determine whether to retry if (! retryTimes | | _ _ retryCount > = retryTimes) {return Promise.reject (err);} _ _ retryCount++; / / increase the number of retries / / delay processing const delay = new Promise ((resolve) = > {setTimeout () = > {resolve () }, retryDelay);}); / / re-initiate the request return delay.then (() = > {return request ();});}}; return request ();};}
The above code is not complex, and the core processing logic is shown in the following figure:
2.2.2 create an Axios object using the retryAdapterEnhancer function 2.2.1 and configure the adapter option const http = axios.create ({baseURL: "http://localhost:3000/", adapter: retryAdapterEnhancer (axios.defaults.adapter, {retryDelay: 1000,}),}); 2.2.2 send a request using the http object / / the request fails without retrying function requestWithoutRetry () {http.get (" / users ") } / / request failed to retry function requestWithRetry () {http.get ("/ users", {retryTimes: 2});}
Well, how to enhance the xhrAdapter adapter to implement the Axios request retry function has been introduced. Because the complete sample code contains a lot of content, Brother Po will not put the specific code. For those who are interested, you can visit the following address to browse the sample code.
The complete sample code:
Https://gist.github.com/semlinker/979ebc659abacea7aa6c0c44af070afe
Here let's take a look at the running result of the Axios implementation request retry example:
III. Summary
This article describes how to implement a request retry in Axios. Based on the retryAdapterEnhancer function or response interceptor defined in this article, you can easily extend the request retry function.
Axios is a very excellent open source project, there are many places for us to learn and learn from. If you are interested in the design and implementation of the HTTP interceptor within Axios, the design and implementation of the HTTP adapter, and how to defend against CSRF attacks, you can read this article on what is worth learning from the 77.9k Axios project.
This is the end of the content of "how to request a retry with Axios". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.