Nothing Special   »   [go: up one dir, main page]

CN118626066A - Axios request library packaging method, system, equipment and storage medium - Google Patents

Axios request library packaging method, system, equipment and storage medium Download PDF

Info

Publication number
CN118626066A
CN118626066A CN202410835013.4A CN202410835013A CN118626066A CN 118626066 A CN118626066 A CN 118626066A CN 202410835013 A CN202410835013 A CN 202410835013A CN 118626066 A CN118626066 A CN 118626066A
Authority
CN
China
Prior art keywords
request
global
configuration
response
setting
Prior art date
Legal status (The legal status is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the status listed.)
Pending
Application number
CN202410835013.4A
Other languages
Chinese (zh)
Inventor
李晓煌
周超
Current Assignee (The listed assignees may be inaccurate. Google has not performed a legal analysis and makes no representation or warranty as to the accuracy of the list.)
Pacific Insurance Technology Co Ltd
Original Assignee
Pacific Insurance Technology Co Ltd
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Pacific Insurance Technology Co Ltd filed Critical Pacific Insurance Technology Co Ltd
Priority to CN202410835013.4A priority Critical patent/CN118626066A/en
Publication of CN118626066A publication Critical patent/CN118626066A/en
Pending legal-status Critical Current

Links

Landscapes

  • Storage Device Security (AREA)

Abstract

The application provides a Axios request library packaging method, a system, equipment and a storage medium, which relate to the technical field of front-end component development, and the Axios packaging method provides a safer and more efficient solution compared with the prior packaging technology in the industry through global loading configuration, dynamic keys and encryption requests for preventing replay attacks. The global loading configuration simplifies service codes, effectively avoids the bug which forgets to close the loading, and improves the stability of the application and the user interaction experience. Meanwhile, the dynamic key encryption and replay attack prevention technology is adopted, so that the safety of the request is obviously improved, the data leakage, the tampering and the request replay are prevented, and the system stability and the user data safety are ensured. In addition, the packaging method is easy to expand and integrate, and provides a flexible and powerful HTTP request processing tool for developers.

Description

Axios request library packaging method, system, equipment and storage medium
Technical Field
The present application relates to the field of front end component development technologies, and in particular, to a Axios request library packaging method, system, device, and storage medium.
Background
Front-end and back-end separation has become a common architecture model in Web development. In this mode, the front-end application needs frequent data interactions with the back-end service, typically implemented through HTTP requests. Axios is a popular Promise-based HTTP client, widely used in browser and node. Js environments, and is favored by developers because of its simplicity and ease of use.
However, while Axios itself provides the basic request function, in practical applications, the developer is faced with the following issues, security: the HTTP request may be intercepted during transmission, and sensitive data such as user information, authentication credentials, etc. may be compromised; data integrity problem: under an open network environment, the request data may be tampered, affecting the accuracy of the data; replay attack: an attacker may capture and replay requests, performing unauthorized operations on the system; user experience problem: during request processing, lack of an effective user feedback mechanism, such as a load indication, may result in poor user experience; exception handling: lack of a unified exception handling mechanism makes error handling decentralized and non-canonical.
In order to solve these problems, some attempts to perform secondary encapsulation on Axios have been made in the prior art, but the functions of these encapsulation libraries are not perfect enough, and the encryption system is crude.
Disclosure of Invention
In view of the above problems, the present application provides a Axios request library packaging method, which includes the following steps:
In a first aspect, the present application provides a Axios request library encapsulation method, the method including:
initializing Axios an instance object, and carrying out default global parameter configuration according to the instance object;
Setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration;
Creating a request object, and adding a general request method, a global request configuration method, a global exception handling method and a global update token method into the request object to obtain a created request object;
exposing publicly accessible methods in the created request object.
Optionally, the performing global parameter configuration includes:
at least, whether to display loading animation configuration, whether to display log configuration, encryption and decryption configuration, global token name configuration and encrypted parameter field name configuration are carried out.
Optionally, after setting a request interceptor in the instance object, the method further includes:
Setting error processing logic in the request interceptor, ending the request and returning a response code when the request is abnormal;
Judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration;
Judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, the dynamic key is obtained to encrypt the request parameter.
Optionally, after setting a response interceptor in the instance object, the method further comprises:
Setting general request error processing logic in the response interceptor, and when the response is abnormal, intercepting the response according to the code corresponding to the response and returning abnormal information;
Setting a closing loading animation logic in the response interceptor, wherein the closing loading animation logic is used for closing loading animation when a response is received;
Checking a response head, namely checking whether the response head contains token information or not, and if so, calling a token setting method of the request object, updating a locally stored token, and ensuring that each request is the latest token; analyzing the response body, and judging the response body according to preset business logic; if the judgment result is abnormal, entering an abnormal logic processing program; if the judgment result is normal, entering a subsequent normal logic processing program;
and after the response is successful, judging whether the request is an encryption request, if so, decrypting the request after receiving the response.
Optionally, the creating a request object, adding a general request method, a global request configuration method, a global exception handling method and a global update token method in the request object, and obtaining the created request object includes:
setting a post method, wherein the post method is used for sending a post request; setting a get method, wherein the get method is used for sending a get request; setting a global request configuration method for realizing request global configuration; the global definition exception handling method is used for realizing global exception configuration; a set Token method is set for setting Token information.
In a second aspect, the present application provides a Axios request library packaging system, the system comprising:
the initialization unit is used for initializing Axios the instance object and carrying out default global parameter configuration according to the instance object;
the setting unit is used for setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration;
the creation unit is used for creating a request object, and adding a general request method, a global request configuration method, a global exception handling method and a global update token method into the request object to obtain a created request object;
and the processing unit is used for exposing the publicly accessible method in the created request object.
Optionally, the setting unit is specifically configured to at least perform whether to display the loading animation configuration, whether to display the log configuration, the encryption and decryption configuration, the global token name configuration, and the encrypted parameter field name configuration.
Optionally, the setting unit is further configured to set error processing logic in the request interceptor after setting the request interceptor in the instance object, and when an exception occurs in the request, end the request and return a response code;
Judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration;
Judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, acquiring a dynamic key to encrypt the request parameter;
Setting a request header, wherein the request header comprises a request header for realizing encryption, a request header for preventing replay attack, a token request header name for global configuration and other header configurations.
Optionally, after the setting unit sets a response interceptor in the instance object, the setting unit is further configured to set general request error processing logic in the response interceptor, and when the response is abnormal, perform response interception according to a code corresponding to the response, and return abnormal information;
Setting a closing loading animation logic in the response interceptor, wherein the closing loading animation logic is used for closing loading animation when a response is received;
checking a response head, namely checking whether the response head contains token information or not, and if so, calling a token setting method of the request object, updating a locally stored token, and ensuring that each request is the latest token;
analyzing the response body, and judging the response body according to preset business logic; if the judgment result is abnormal, entering an abnormal logic processing program; if the judgment result is normal, entering a subsequent normal logic processing program;
and after the response is successful, judging whether the request is an encryption request, if so, decrypting the request after receiving the response.
Optionally, the creating unit is configured to create a request object, add a general request method to the request object, and obtain a created request object includes: setting a post method, wherein the post method is used for sending a post request; setting a get method, wherein the get method is used for sending a get request; setting a global request configuration method for realizing request global configuration; the global definition exception handling method is used for realizing global exception configuration; a set Token method is set for setting Token information.
In a third aspect, the present application provides an apparatus, the apparatus comprising a memory for storing instructions or code and a processor for executing the instructions or code to cause the apparatus to perform the Axios request library encapsulation method introduced in any implementation of the first aspect.
In a fourth aspect, the present application provides a computer readable storage medium having code stored therein, which when executed, implements the Axios request library encapsulation method introduced in any one of the implementations of the first aspect.
The application provides a Axios request library packaging method. When the method is executed, firstly initializing Axios an instance object, and carrying out default global parameter configuration according to the instance object; setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration; creating a request object, and adding a general request method into the request object to obtain the created request object; exposing publicly accessible methods in the created request object. The Axios encapsulation method provides a safer and more efficient solution compared with the prior encapsulation technology in the industry through global loading configuration, dynamic key encryption and replay attack prevention. The global loading configuration simplifies service codes, effectively avoids the bug which forgets to close the loading, and improves the stability of the application and the user interaction experience. Meanwhile, the dynamic key encryption and replay attack prevention technology remarkably improves the safety of the request, prevents data leakage and tampering, and ensures the system stability and the user data safety. In addition, the packaging method is easy to expand and integrate, and provides a flexible and powerful HTTP request processing tool for developers.
Drawings
In order to more clearly illustrate this embodiment or the technical solutions of the prior art, the drawings that are required for the description of the embodiment or the prior art will be briefly described, it being obvious that the drawings in the following description are only some embodiments of the present application, and that other drawings may be obtained according to these drawings without inventive effort for a person skilled in the art.
FIG. 1 is a flowchart of a Axios request library packaging method according to an embodiment of the present application;
Fig. 2 is a schematic structural diagram of a Axios request library packaging system according to an embodiment of the present application.
Detailed Description
In order to make the objects, technical solutions and advantages of the embodiments of the present application more apparent, the technical solutions of the embodiments of the present application will be clearly and completely described below with reference to the accompanying drawings in the embodiments of the present application, and it is apparent that the described embodiments are only some embodiments of the present application, not all embodiments. All other embodiments, which can be made by those skilled in the art based on the embodiments of the application without making any inventive effort, are intended to be within the scope of the application.
Fig. 1 is a flowchart of a Axios request library packaging method according to an embodiment of the present application. Referring to fig. 1, a method for packaging Axios request library according to an embodiment of the present application may include:
S101, initializing Axios an instance object, and carrying out default global parameter configuration according to the instance object.
Axios is a Promise based HTTP client for browsers and nodes. It is isomorphic (isomorphic), i.e., the same set of code can run in both browser and node.
An instance object refers to an instance of a particular Axios environment created by Axios constructors. The user may create different Axios instances for different portions of each application (e.g., front end and configure them to use different URLs, request headers, timeout settings, etc.).
Global parameter configuration refers to default parameters and settings set for Axios instance objects that will apply to all requests issued by the instance. For example, a default request header, baseURL, timeout time, etc. may be set.
In an implementation method of the embodiment of the present application, the performing global parameter configuration includes:
at least, whether to display loading animation configuration, whether to display log configuration, encryption and decryption configuration, global token name configuration and encrypted parameter field name configuration are carried out.
Whether to display a load animation configuration refers to the fact that when an application performs some time consuming operation (e.g., loading data, submitting a form, etc.), a load animation is typically displayed in order to give the user feedback. This configuration allows the developer to decide whether to display such an animation at a particular operation or page load. When an application makes a network request or other time consuming operation, displaying the load animation may let the user know that the application is still running and waiting for a response, rather than seizing or not responding. This reduces anxiety of the user, improving usability and responsiveness of the application.
Whether to display a log configuration determines whether the application records and displays log information. Journaling is important for debugging, monitoring and tracking problems. The developer can choose which information to record (e.g., errors, warnings, messages, debug, etc.) as desired, and whether such information should be displayed directly to the user or viewed only in the background. Logging can help a developer track the running status of an application, knowing when and where a particular event or error occurred. By looking at the log, the developer can quickly locate the problem, analyze the cause and repair. In addition, the log may also be used to monitor the performance of the application and user behavior.
Encryption and decryption configuration, in many applications, especially when sensitive information (such as user password, payment information, etc.) is involved, encryption and decryption are key to ensuring data security. The encryption and decryption configuration allows a developer to specify which encryption algorithm, a key management policy, and when data is encrypted or decrypted, and in one implementation method of the embodiment of the present application, the encryption mode is SM4, the key is dynamically obtained, a new key is generated when each request is made, the key is transmitted to the backend key in a request header manner through SM2 encryption, and the request parameter SM4 is transmitted to the backend after encryption. The encryption method is important for protecting the privacy of users and adhering to the data protection regulations.
Global token name configuration in many modern Web applications, token (e.g., JWT, OAuth token, etc.) is used as a mechanism for authentication and authorization. The global token name configuration allows a developer to specify the name or identifier of a token for authentication in an application. Thus, when an application needs to verify the identity of a user or authorize access to a resource, it can look up and verify a token with a specified name.
Encrypted parameter field name configuration that allows a developer to specify the field names that these encrypted parameters should use in a request when an application needs to encrypt and send certain parameters to a server. This helps the server to properly parse and verify these encryption parameters.
Request header configuration the request header (HTTP HEADERS) is an important component of the HTTP request, containing various meta-information about the request. The request header configuration allows the developer to set custom request headers for HTTP requests issued by the application. These request headers may include authentication information (e.g., authorization header), content Type (Content-Type), cache Control (Cache-Control), etc. By properly configuring the request header, which in the embodiments of the present application refers to the common request header that needs to be set for the request, the developer can ensure that the communication between the application and the server conforms to the desired protocol and behavior.
The configuration options of whether to print the request log allow the request parameters before encryption and the response parameters after decryption to be selected according to the configuration in the development environment and the test environment, thereby assisting the research personnel to more effectively troubleshoot the problem.
In addition, the relevant configuration may be performed according to the actual situation, for example, whether to automatically load, and the attribute name of the header stored in the token, that is, the custom configuration may be performed according to the actual use requirement, where the configuration content listed in the embodiment is merely exemplary.
S102, setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result.
The request interceptor is set up by setting up at least a global loading hint, an encryption function and completing request header configuration.
After the instance object and the global parameter configuration are completed, a request interceptor and a response interceptor are further arranged in the instance object so as to realize global processing of the request and the response. The method comprises the steps of setting a global loading prompt and an encryption function when the request interceptor is set, so that the loading animation can be automatically displayed when a network request is initiated, and encryption processing is carried out on request data, thereby improving user experience and data security.
The request interceptor (Request Interceptors) and response interceptor (Response Interceptors) are functions common in network request libraries such as Axios, okHttp, retrofit, etc., that allow specific operations to be performed before a request is sent to a server or after a response is returned from a server.
The request interceptor (Request Interceptors) is for being invoked before the request is sent to the server. Some operations may be performed with the request interceptor, such as:
request exception interception, such as when an exception occurs in a request, an exception such as a network failure occurs; adding a global request header (e.g., authentication token, user agent, etc.); processing the request data, such as serialization, encryption, etc.; displaying or hiding UI elements (e.g., loading animations) to inform the user that a request is in progress; cancel request (if certain conditions are met); the request configuration (e.g., URL, request method, request body, etc.) is modified. Request interceptors are where global request logic is handled, since they are invoked each time a network request is initiated.
The response interceptor (Response Interceptors) is invoked before the response is returned from the server and passed to the requestor, with which some operations may be performed, such as: processing the response data, such as deserializing, decrypting, etc.; validating the response status code and performing different operations (e.g., redirecting, displaying error messages, etc.) accordingly; hiding UI elements (e.g., loading animations) to inform the user that the request has been completed; modify response data or configuration (if needed); response interceptors are very useful in processing server responses, especially when unified processing (e.g., data formatting, error handling, etc.) of the response is required.
The following describes the function of the request interceptor configuration in the present application with reference to specific embodiments:
When a request interceptor is set, error processing logic is required to be set in the request interceptor, and the processing logic is used for ending the request and returning a response code when the request is abnormal; judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration; judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, acquiring a dynamic key to encrypt the request parameter; setting a request header, wherein the request header comprises a request header for realizing encryption, a request header for preventing replay attack, a token request header name for global configuration and other header configurations.
Error handling logic, when an exception occurs in a request during transmission or processing (e.g., network failure, server error, etc.), the request interceptor will capture the exception and execute preset error handling logic to perform error handling, in which logic the exception request is terminated and a response with a specific response code (e.g., 10000) is returned to the caller to identify that it is a request exception. The response code can be customized according to the actual requirements of the project.
In addition, the request interceptor will determine from one of the parameters in the global configuration (e.g., isShowLoading) whether a load animation needs to be displayed at the time of request transmission. If configured to be on (default to on), then when the request is sent, display logic to load the animation is triggered; when a request succeeds or fails and a response is returned, the loading animation is hidden. Thus, better interactive experience can be provided for the user, and the user perceives that the request is being processed.
The request interceptor also determines whether the request parameters need to be encrypted based on the encryption and decryption fields (e.g., crypto) in the global configuration and the API path of the request. When encryption conditions are met (e.g., public key publicKey is configured and is a POST request and the request path does not start with unEncrypt), the interceptor generates the key (key) and initialization vector (iv) required for SM4 encryption and encrypts them by SM2 algorithm using the public key. Then, the encrypted keys and iv are added to the request header, and the request parameters are encrypted by using the SM4 algorithm and then transmitted. Therefore, the security of the request parameters in the transmission process can be ensured, and the request parameters are prevented from being stolen or tampered by malicious users. The process of requesting parameter encryption specifically includes:
① Front end encryption
Whether encryption is needed or not is judged according to encryption and decryption configuration crypto and a request api path in the global configuration, and when the configuration contains publicKey (public key) and is that the post request and the request path do not start with unEncrypt, the request is considered to be needed to be encrypted. Key and iv required for SM4 encryption will be randomly generated at each send post request. SM2 encrypting the generated keys and iv with publicKey (public key) in the configuration in the interceptor at the request and adding the encrypted keys and iv to the specified request header. Note that: the name of the request header is named according to headerKeyForSm Key and headerKeyForSm4iv in the configuration. And finally, assigning the request parameters into SM4 encrypted character strings.
② Processing requests
When the back end receives the request, firstly, the Key and iv corresponding to headerKeyForSm Key and headerKeyForSm iv in the request header are decrypted by using SM2 decryption algorithm by using the private Key in the database. And then decrypting the request parameters by using the decrypted key, iv, and processing the service logic.
③ Responding to the request
After the business logic is processed, the key is used, the response data is encrypted by SM4 through iv, and finally the encrypted character string is returned to the front end.
In addition to the encryption requiring the setting of special request HEADERs, the front-end generates a random string containing a time stamp, passing the value to the back-end via a request HEADER GATEWAY-DDOS-HEADER that is co-negotiated with the back-end in order to prevent replay attacks. In addition, the token request header names and other header configurations in the global configuration are also uniformly set according to the configuration.
① Processing requests
If the back end receives the GATEWAY-DDOS-HEADER request head, firstly obtaining the value of the request head, and comparing the timestamp in the value with the current time:
A. If the time stamp is 30 minutes earlier than the current time, the system time in the request head is considered to be wrong, and the request fails;
B. If the time stamp is more than one hour later than the current time, the system time in the request head is considered to exceed the failure time, and the request fails;
C. If the time stamp is valid, judging whether the value of the request header exists in the redis cache, if so, indicating that the request is a repeated request, and if not, judging that the request is a first request, and if not, storing the value in the redis cache.
The above configuration and logic enhances the functionality of the request interceptor, enabling it to better handle abnormal situations, provide a user friendly interactive experience, and protect the security of the request parameters. Implementation of these configurations and logic requires detailed planning and design by developers according to actual requirements of the project.
In one implementation method of the embodiment of the present application, after setting a response interceptor in the instance object, the method further includes:
Setting general request error processing logic in the response interceptor, and when the response is abnormal, intercepting the response according to the code corresponding to the response and returning abnormal information; setting a closing loading animation logic in the response interceptor, wherein the closing loading animation logic is used for closing loading animation when a response is received;
Checking a response head, namely checking whether the response head contains token information or not, and if so, calling a token setting method of the request object, updating a locally stored token, and ensuring that each request is the latest token; analyzing the response body, and judging the response body according to preset business logic; if the judgment result is abnormal, entering an abnormal logic processing program; if the judgment result is normal, entering a subsequent normal logic processing program; and after the response is successful, judging whether the request is an encryption request, if so, decrypting the request after receiving the response.
In Axios, the response may be processed by setting a response interceptor (response. Use). When responding to an anomaly (such as a network error, a server error, etc.), the anomaly can be judged by checking an HTTP status code (such as a non-2 xx status code), and customized anomaly information is returned. It should be noted that, whether the response succeeds or fails, the loading should be closed at the end of the interceptor. This typically involves invoking a function or method that controls the display or hiding of the loading animation, e.g., by global load hint field isShowLoading in a global setting to determine if it is unified to request that the loading animation be added, default to on.
When the HTTP request returns, the response interceptor first checks the status code of the response, for example, HTTP status code 200 indicates success, and 4xx or 5xx indicates different types of errors, if the response status code indicates abnormality (not 200), the interceptor searches the corresponding abnormality information according to the preset serverErrorMap dictionary, and returns the information to the front-end user or performs other error processing. Exemplary description is given below of a serverErrorMap dictionary provided in an embodiment of the present application, according to which the serverErrorMap dictionary may be used to match status codes and errors, where the serverErrorMap dictionary is as follows:
[400, "request error (400)" ], [401, "unauthorized (401)" ], [403, "" refusal (403) "], [404," address not present (404) "], [408," "request timeout (408)", [500, "" server error (500) ", [501," "service not achieved (501)", [502, "" network error (502) "], [503," "service not available (503)", [504, "" network timeout (504) ", [505," "HTTP version not supported (505)", [999, "" connection server failed "], [90001," response data structure not legal "".
The close load animation logic, whether the HTTP request is successful or failed, is executed by the response interceptor. This is because loading an animation is typically used to instruct the user to wait for a response, and once a response arrives, the loading of the animation should be stopped regardless of the result.
Token management, the response interceptor will check if the response header contains token information (e.g., JWT token). If a new token is included in the response header, the token in the local store needs to be updated to the new token.
The business logic judges that when the HTTP request is successful, the interceptor analyzes the response body. According to a predetermined service logic determination method (e.g., decideLogic), the interceptor checks a specific field (e.g., success field) in the response body to determine whether the service processing is successful. If success is false, indicating that the service is handling exception, the interceptor will call the exception logic handler. If success is true, which indicates that the service is processed normally, the interceptor will enter the subsequent normal logical processing program.
If the request is an encryption request (e.g., using HTTPS or other encryption technique) and the back-end returned data is also encrypted, the response interceptor will decrypt the response after receiving the response. The decryption process requires parameters such as a key and an initialization vector (iv). To better parse the decrypted data, the backend may add a field to the response to indicate the type of data (e.g., object, string, etc.). Without this field, the front end would default to parsing the data using JSON format.
Through the steps, the response interceptor can provide a unified and flexible mechanism for processing the response of the HTTP request, including functions of error processing, loading animation control, token management, business logic judgment, data decryption and the like. This helps to improve the stability and user experience of the front-end application.
S103, creating a request object, and adding a general request method into the request object to obtain the created request object.
After the interceptor method is registered for axios examples, further request object creation is performed, and a general request method is added, including a post method for sending a post request, a get method for sending a get request, a setRequestGlobalConfig method for setting global request configuration, including setSpecialError for globally defining an exception handling method, and a setToken method for setting token information.
⑴ Post definition method
The method requires url of the incoming request and must be transmitted, and the request parameters params and global configuration config are not necessarily transmitted. The return reference is Promise returned by the axios.request method, and the user can process own business logic after receiving the return reference. The post request defaults to an encrypted request, in which keys and iv are randomly acquired each time, and are transmitted together with url, params, config parameters when an axios request method is called, and the encrypted request is used for performing operations such as parameter encryption on the request in request interception. Logic to add the print log after a request is successful or abnormal if the print request log is configured in the global configuration. And, the global request exception method set by setSpecialError is executed after the request exception, so as to globally process exceptions, such as unregistered, network exceptions, and the like.
⑵ Get definition method
The method is similar to the get method for sending get requests. The necessary parameters are defined as request path url, the unnecessary parameters params and global configuration config. The request method of axios instance is called according to these entries and Promise of the method is returned.
⑶ Definition setRequestGlobalConfig method
The method is mainly used for user-defined setting of global request configuration, such as whether to print logs, encrypt and decrypt configuration, global token names, whether to start global loading, a global loading starting method, a loading closing method and the like. Then, according to these configurations, a global request interception method and a response interception method are registered for axios instances.
⑷ Definition setSpecialError method
The method is mainly used for user-defined global exception handling methods, such as exception handling logic when the user is not logged in, or logged in is aged, or network is abnormal, or system upgrading and other global exceptions. Such as skip log-in pages when not logged in, network exception skip network failure pages, etc., without reprocessing these common logic in all request method responses.
⑸ Definition setToken method
The method is mainly used for setting the token by a user, and if the back end returns the token in a response head, the method does not need to be called, because a response interception method is registered for axois examples, after the response is successful, the token can be written back each time, the latest token is ensured each time, and if the token is not in the response head, the user is required to call the method to set the token.
S104, exposing the configured request object through a request object interface accessed by external disclosure.
When a request object is configured, the configured request object is typically exposed through an interface for public access in order to enable it to be conveniently invoked and used throughout the business project. This has several major benefits: unified interface: by exposing the unified interface, each module or component in the business engineering can initiate an HTTP request through the same interface, thereby ensuring the consistency of request behaviors; the use is convenient: the developer does not need to care about the implementation details of the bottom HTTP request any more, and can initiate the HTTP request and process the response result only by calling the interface and transmitting corresponding parameters; easy to maintain: if the HTTP request needs to be globally modified or expanded, only the configuration or implementation of the request object needs to be modified, and each place using the HTTP request does not need to be modified; safety: through the externally exposed interface, some security checksum restrictions, such as permission checking, request frequency restriction, etc., can be added, thereby protecting the system from attacks by malicious requests.
The above embodiment describes the encapsulation process of Axios request library encapsulation, and in order to enable those skilled in the art to further understand the scheme, the following describes in detail how to use the encapsulated and exposed global single instance request object in the business engineering:
1. In business engineering, in order to uniformly manage and use HTTP requests, a module related to requests is generally customized, and a globally unique single instance request object in the module is introduced into a place where the HTTP requests need to be used. This has the advantage of ensuring that the behaviour and configuration of HTTP requests is consistent throughout the traffic engineering.
Request object for introducing global singleton
import request from'@share/request';
2. After the request object is introduced, the global configuration method is called, and the global configuration requested in the service engineering can be set by calling the setRequestGlobalConfig method provided by the request object. These configurations may include whether to print the request log, set a specific request header, whether to turn on the global loading effect, the display and hiding method of the loading effect, the serialization manner of the request parameters, etc. The method can be realized by the following codes:
Setting global configuration
request.setRequestGlobalConfig({
Judging whether to print request log according to environment variable
showLog:['development','sit'].includes(CURRENT_ENV),
Setting specific request header
headers:{
'GATEWAY-CHANNEL-HEADER':'TEST',
},
Load effect is/is not automatically displayed
isShowLoading:true,
Method for serializing/requesting parameters
paramString:'base-template',
Name of request header of/(token)
tokenHeaderName:tokenHeaderName,
Time delay duration before display of the load effect
delayShow:300,
Method for displaying/(custom loading effect)
startLoadingFun:()=>{/*...*/},
Method for hiding/(custom loading effect)
stopLoadingFun:()=>{/*...*/},
Other global configurations.
}as unknown as RequestGlobalConfig);
3. Method for processing defined global exception
When an HTTP request is in error, it may be necessary to perform some specific operation, such as jumping to a log-in page, a system upgrade page, etc. The callback function handling the exception condition may now be imported by calling the request.setspecialty error method, which will execute in the requested. Catch method.
Method for handling/defining global exception
export function specialError(ex:SystemError):void{
Performing different operations according to error codes
const{code}=ex||{};
if(code==='403'||code===403){
Jump to login page
}else if(code==='777'||code===777){
System upgrade page is/is jumped to
}
Handling of other error codes
A throw ex; the exception is reissued so that the upper layers can continue to handle
}
Method for handling/setting global exception
request.setSpecialError(specialError);
4. Sending a request
After the global parameters and exception handling methods are configured, the request object may be used to send an HTTP request. Depending on the request type (GET, POST, etc.), different methods may be selected and the corresponding parameters entered. For example, the parameters of a GET request are typically placed in the query string of a URL, while the parameters of a POST request are placed in the request body.
Example of/send GET request
import request from'@share/request';
request.get('/api/someEndpoint',{params:{id:123}})
.then(response=>{
Response data is/are processed
})
.catch(error=>{
Request error handling/handling
});
Example of a/send POST request
request.post('/api/anotherEndpoint',{data:{name:'John'}})
.then(response=>{
Response data is/are processed
})
.catch(error=>{
Request error handling/handling
});
The method described in the above embodiment can be used by a developer to pay more attention to the implementation of business logic through global configuration and exception handling, without spending too much time on the underlying network request processing.
The embodiment of the application provides some specific implementation manners of Axios request library sealing methods, and based on the specific implementation manners, the application also provides a corresponding system. The system provided by the embodiment of the application will be described from the aspect of functional modularization.
Fig. 2 is a schematic structural diagram of a Axios request library packaging system according to an embodiment of the present application.
Referring to fig. 2, a Axios request library packaging system 200 according to an embodiment of the present application includes:
an initializing unit 210, configured to initialize Axios an instance object, and perform default global parameter configuration according to the instance object;
A setting unit 220, configured to set a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration;
a creating unit 230, configured to create a request object, and add a general request method, a global request configuration method, a global exception handling method, and a global update token method to the request object, so as to obtain a created request object;
and a processing unit 240, configured to expose a publicly accessible method in the created request object.
In an implementation method of the embodiment of the present application, the setting unit is specifically configured to at least perform whether to display a loading animation configuration, whether to display a log configuration, an encryption and decryption configuration, a global token name configuration, and an encrypted parameter field name configuration.
In an implementation method of the embodiment of the present application, after the setting unit sets a request interceptor in the instance object, the setting unit is further configured to set error processing logic in the request interceptor, and when an exception occurs in a request, end the request and return a response code;
Judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration;
Judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, acquiring a dynamic key to encrypt the request parameter;
Setting a request header, wherein the request header comprises a request header for realizing encryption, a request header for preventing replay attack, a token request header name for global configuration and other header configurations.
In one implementation method of the embodiment of the present application, after the setting unit sets a response interceptor in the instance object, the setting unit is further configured to set general request error processing logic in the response interceptor, and when the response is abnormal, perform response interception according to a code corresponding to the response, and return abnormal information;
Setting a closing loading animation logic in the response interceptor, wherein the closing loading animation logic is used for closing loading animation when a response is received;
checking a response head, namely checking whether the response head contains token information or not, and if so, calling a token setting method of the request object, updating a locally stored token, and ensuring that each request is the latest token;
analyzing the response body, and judging the response body according to preset business logic; if the judgment result is abnormal, entering an abnormal logic processing program; if the judgment result is normal, entering a subsequent normal logic processing program;
and after the response is successful, judging whether the request is an encryption request, if so, decrypting the request after receiving the response.
In an implementation method of the embodiment of the present application, the creating unit is configured to create a request object, add a general request method to the request object, and obtain a created request object includes: setting a post method, wherein the post method is used for sending a post request; setting a get method, wherein the get method is used for sending a get request; setting a global request configuration method for realizing request global configuration; the global definition exception handling method is used for realizing global exception configuration; a set Token method is set for setting Token information.
The embodiment of the application also provides corresponding equipment and a computer storage medium, which are used for realizing the scheme provided by the embodiment of the application.
The device comprises a memory for storing instructions or code and a processor for executing the instructions or code to cause the device to perform the method according to any of the embodiments of the present application.
The computer storage medium has code stored therein that, when executed, causes an apparatus for executing the code to perform the method of any of the embodiments of the present application.
From the above description of embodiments, it will be apparent to those skilled in the art that all or part of the steps of the above described example methods may be implemented in software plus general hardware platforms. Based on such understanding, the technical solution of the present application may be embodied in the form of a software product, which may be stored in a storage medium, such as a read-only memory (ROM)/RAM, a magnetic disk, an optical disk, etc., and includes several instructions for causing a computer device (which may be a personal computer, a server, or a network communication device such as a router) to perform the method according to the embodiments or some parts of the embodiments of the present application.
It is noted that relational terms such as first and second, and the like are used solely to distinguish one entity or action from another entity or action without necessarily requiring or implying any actual such relationship or order between such entities or actions. Moreover, the terms "comprises," "comprising," or any other variation thereof, are intended to cover a non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements does not include only those elements but may include other elements not expressly listed or inherent to such process, method, article, or apparatus. Without further limitation, an element defined by the phrase "comprising one … …" does not exclude the presence of other like elements in a process, method, article, or apparatus that comprises the element.
It should be further noted that, in the present specification, each embodiment is described in a progressive manner, and identical and similar parts of each embodiment are all referred to each other, and each embodiment mainly describes differences from other embodiments. In particular, for the apparatus and system embodiments, since they are substantially similar to the method embodiments, the description is relatively simple, with reference to the description of the method embodiments in part. The above-described apparatus and system embodiments are merely illustrative, in which elements illustrated as separate elements may or may not be physically separate, and elements illustrated as elements may or may not be physical elements, may be located in one place, or may be distributed over a plurality of network elements. Some or all of the modules may be selected according to actual needs to achieve the purpose of the solution of this embodiment. Those of ordinary skill in the art will understand and implement the present invention without undue burden.
The foregoing is only one specific embodiment of the present application, but the scope of the present application is not limited thereto, and any changes or substitutions easily contemplated by those skilled in the art within the technical scope of the present application should be included in the scope of the present application. Therefore, the protection scope of the present application should be subject to the protection scope of the claims.

Claims (10)

1. A method of Axios request library encapsulation, the method comprising:
initializing Axios an instance object, and carrying out default global parameter configuration according to the instance object;
Setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration;
Creating a request object, and adding a general request method, a global request configuration method, a global exception handling method and a global update token method into the request object to obtain a created request object;
exposing publicly accessible methods in the created request object.
2. The method of claim 1, wherein the performing global parameter configuration comprises:
at least, whether to display loading animation configuration, whether to display log configuration, encryption and decryption configuration, global token name configuration and encrypted parameter field name configuration are carried out.
3. The method of claim 2, wherein setting a request interceptor in the instance object comprises:
Setting error processing logic in the request interceptor, ending the request and returning a response code when the request is abnormal;
Judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration;
judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, acquiring a dynamic key to encrypt the request parameter; setting a request header, wherein the request header comprises a request header for realizing encryption, a request header for preventing replay attack, a token request header name for global configuration and other header configurations.
4. The method of claim 2, wherein setting a response interceptor in the instance object comprises:
Setting general request error processing logic in the response interceptor, and when the response is abnormal, intercepting the response according to the code corresponding to the response and returning abnormal information;
Setting a closing loading animation logic in the response interceptor, wherein the closing loading animation logic is used for closing loading animation when a response is received;
checking a response head, namely checking whether the response head contains token information or not, and if so, calling a token setting method of the request object, updating a locally stored token, and ensuring that each request is the latest token;
analyzing the response body, and judging the response body according to preset business logic; if the judgment result is abnormal, entering an abnormal logic processing program; if the judgment result is normal, entering a subsequent normal logic processing program;
and after the response is successful, judging whether the request is an encryption request, if so, decrypting the request after receiving the response.
5. The method of claim 1, wherein creating the request object, adding a general request method, a global request configuration method, a global exception handling method, and a global update token method to the request object, and obtaining the created request object comprises:
setting a post method, wherein the post method is used for sending a post request; setting a get method, wherein the get method is used for sending a get request; setting a global request configuration method for realizing request global configuration; the global definition exception handling method is used for realizing global exception configuration; a set Token method is set for setting Token information.
6. A Axios request library packaging system, the system comprising:
the initialization unit is used for initializing Axios the instance object and carrying out default global parameter configuration according to the instance object;
the setting unit is used for setting a default request interceptor and a response interceptor in the instance object according to the global parameter configuration result; the request interceptor is set up by setting up at least global loading prompt, encryption function and completing request head configuration;
the creation unit is used for creating a request object, and adding a general request method, a global request configuration method, a global exception handling method and a global update token method into the request object to obtain a created request object;
And the processing unit exposes a publicly accessible method in the created request object.
7. The system according to claim 6, wherein the setting unit is specifically configured to perform at least a display of a loading animation configuration, a display of a log configuration, an encryption/decryption configuration, a global token name configuration, and an encrypted parameter field name configuration.
8. The system of claim 7, wherein the setting unit is further configured to set error handling logic in the request interceptor after setting the request interceptor in the instance object, and when an exception occurs in a request, end the request and return a response code;
Judging whether to unify to request to add the loading animation according to whether to display the loading animation field in the global parameter configuration;
Judging whether encryption is carried out or not according to the encryption and decryption fields and the request path in the global parameter configuration; if yes, acquiring a dynamic key to encrypt the request parameter;
Setting a request header, wherein the request header comprises a request header for realizing encryption, a request header for preventing replay attack, a token request header name for global configuration and other header configurations.
9. An electronic device, the electronic device comprising: a memory, a processor, a display and a Axios request library wrapper stored on the memory and executable on the processor, the Axios request library wrapper when executed by the processor implementing the steps of the method of Axios request library wrapper of any one of claims 1-5.
10. A computer readable storage medium, wherein the computer readable storage medium stores a request library encapsulation program based on Axios, the request library encapsulation program of Axios, when executed by a processor, implementing the steps of the request library encapsulation method of Axios according to any one of claims 1-5.
CN202410835013.4A 2024-06-25 2024-06-25 Axios request library packaging method, system, equipment and storage medium Pending CN118626066A (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
CN202410835013.4A CN118626066A (en) 2024-06-25 2024-06-25 Axios request library packaging method, system, equipment and storage medium

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
CN202410835013.4A CN118626066A (en) 2024-06-25 2024-06-25 Axios request library packaging method, system, equipment and storage medium

Publications (1)

Publication Number Publication Date
CN118626066A true CN118626066A (en) 2024-09-10

Family

ID=92608023

Family Applications (1)

Application Number Title Priority Date Filing Date
CN202410835013.4A Pending CN118626066A (en) 2024-06-25 2024-06-25 Axios request library packaging method, system, equipment and storage medium

Country Status (1)

Country Link
CN (1) CN118626066A (en)

Similar Documents

Publication Publication Date Title
US9418218B2 (en) Dynamic rendering of a document object model
US8844043B2 (en) Detection of vulnerabilities in computer systems
Mainka et al. Penetration testing tool for web services security
US20230259386A1 (en) Data processing method based on container engine and related device
US20120216133A1 (en) Secure cloud computing system and method
WO2005069823A2 (en) Centralized transactional security audit for enterprise systems
CN111625301A (en) Idempotent processing method, apparatus, device and storage medium
EP4254867A2 (en) Method, product, and system for analyzing attack paths in computer network generated using a software representation that embodies network configuration and policy data for security management
CN110083338B (en) Service system based on intelligent gateway
CN110166459A (en) A kind of means of defence and device of unserializing loophole
US9009534B2 (en) Runtime configuration checks for composite applications
CN114598481B (en) Authorization authentication method and device, electronic equipment and storage medium
CN109271807A (en) The data safety processing method and system of database
CN115580413B (en) Zero-trust multi-party data fusion calculation method and device
US11770363B2 (en) Systems and methods for secure access smart hub for cyber-physical systems
US9418167B2 (en) System and method for invoking web services from command-line program
Zhu et al. A model-based aspect-oriented framework for building intrusion-aware software systems
CN118626066A (en) Axios request library packaging method, system, equipment and storage medium
Del Vecchio et al. Evaluating Grid portal security
Yang et al. A model-based fuzz framework to the security testing of TCG software stack implementations
CN117411729B (en) Oracle database login method, device, computer equipment and medium
US20230319067A1 (en) Method, product, and system for network security management using software representation that embodies network configuration and policy data
US20230318845A1 (en) Method, product, and system for generating detection signatures based on attack paths in a computer network identified using a software representation that embodies network configuration and policy data for security management using detection signature templates
US20230319068A1 (en) Method, product, and system for analyzing a computer network to identify attack paths using a software representation that embodies network configuration and policy data for security management
WO2024212598A1 (en) Non-invasive micro-service system authority control method and system

Legal Events

Date Code Title Description
PB01 Publication
PB01 Publication
SE01 Entry into force of request for substantive examination
SE01 Entry into force of request for substantive examination