As a front-end engineer, it is often necessary to encapsulate axios to meet the purpose of multiplexing. Using the same axios encapsulation in different front-end projects is conducive to maintaining consistency and facilitates the transfer and processing of data. This article provides two ideas for encapsulating axios.
1. Pass the request method as a call parameter
1. First, axios, AxiosInstance and AxiosResponse modules are imported to create an instance of an http request and process response results.
2. Define a getBaseUrl function to get the requested base URL.
3. Created an httpProto instance and use the method to create it. It also configures the requested timeout time to 5000ms, does not carry credentials, sets the requested Content-Type to application/json;charset=UTF-8, and allows cross-domain access.
4. Added a request interceptor to process the request through methods. First use the getBaseUrl function to get the base URL and add it to the requested baseURL property. Then get the credentials through the getToken function, if they exist, add them to the Authorization header field of the request. Finally, return the processed request configuration.
5. Added a response interceptor to process the response through methods. First get the response data field, and then judge the value. If it is 0, it means that the request is successful and data is returned directly. Otherwise, a failed promise will be returned with the value of reject as data.
6. Define an http function to send requests. This function receives a method parameter and other parameters (rest), and then calls the corresponding method of the httpProto instance to send the request through the form httpProto[method](...rest).
7 defines a urls object to store the URL path available, with an example path example.
7. Define a methods object to store commonly used request method names, including get, post and delete.
The complete code looks like this:
import axios, { AxiosInstance, AxiosResponse } from "axios"; import { getToken } from "./token"; // Get the basic URL of the requestconst getBaseUrl = () => `http://${}:8888}`; // Create an instance object for http requestconst httpProto: AxiosInstance = ({ timeout: 5000, withCredentials: false, headers: { 'Content-Type': 'application/json;charset=UTF-8', 'Access-Control-Allow-Origin': '*', } }); // Add a request interceptor((config: any) => { // Configure baseURL = getBaseUrl(); // Get the credentials const token = getToken(); if (token) { // If there is a voucher, add this voucher = `${token}`; } return config; }, (error) => { return (error) }); // Add a response interceptor( (response: AxiosResponse) => { const { data } = response // Unified processing of response results if ( === 0) { return data; } else { return (data); } }, (error) => { // Unified processing of error messages return (error); } ); // Encapsulate the httpProto instance, that is, the AxiosInstance instance objectconst http = (method: string, ...rest: any) => { return httpProto[method](...rest); } // Available urlsconst urls = { example: `/prod/example`, } const methods = { get: 'get', post: 'post', delete: 'delete', } export { http, urls, methods };
2. Directly call the request method corresponding to a certain request method
1. Import the related types and functions of the axios module.
2. The printLog function is defined to handle log output.
3. Define the IResponse interface, representing the format of the request response object.
4. The RequestParams interface is defined, indicating the format of the configuration item that sends the request.
5. Define the IHttp interface, indicating the request method/method supported by the encapsulation object.
6. Define the req object to expose the supported request method outward.
7. The methods array is defined to represent the supported request method type.
8. Use the forEach method to traverse the methods array and gradually construct various methods on the req object.
9. During the construction process of each method, perform the following steps:
- Merge the parameters and set the default responseType to 'json'.
- Deconstruct the required parameters from the params object.
- Use method to create an AxiosInstance instance object.
- Create a request header object and set some commonly used request header information.
- Construct the request configuration object AxiosRequestConfig.
- The request configuration is corrected according to the request method, mainly to assign data to the corresponding field.
- Add a request interceptor and return to the configuration if successful and failed.
- Add a response interceptor and return the processing results in success and failure.
- Constructs a callback function with successful requests to format the return data.
- Constructs a callback function that fails to request and handles error logs and network outages.
- Send the request and use the result of the request as the return value of the function.
10. The req object is exported by default.
Here is the complete code with comments:
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'; // Log processing, customizableconst printLog = console; // Format of the request response object wrapped by Promiseexport interface IResponse { code: number; msg: string; result: { lastOperaTime: number; data: any; }; } // Format of the configuration item that sends the requestexport interface RequestParams { url: string; baseUrl?: string; data?: object; filter?: boolean; responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'; headers?: any; timeout?: number; } // Request method/method supported by encapsulation objectinterface IHttp { get?: (params: RequestParams) => Promise<any>; post?: (params: RequestParams) => Promise<any>; put?: (params: RequestParams) => Promise<any>; patch?: (params: RequestParams) => Promise<any>; delete?: (params: RequestParams) => Promise<any>; } // Supported request method typesexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; // The object exposed to the outsideconst req: IHttp = {}; // Supported request typesconst methods: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete']; // traverse the methods array and gradually construct the req object((_m: HttpMethod) => { // Use traversal to construct various methods on req objects req[_m] = (params: RequestParams) => { // 1. Construct parameter merging params = { ...params, responseType: || 'json', }; // 2. Structure the necessary parameters from the formal parameters using the object method const { url, // Server address data, // Payload filter = true, // Filter responseType, // Return type timeout, // Timeout time } = params; // 3. Create AxiosInstance instance object using axios const instance = ({ baseURL: ?? `http://${}`, timeout, }); // 4. Create a request header object const headers = { lastOperaTime: (), // Time stamp token: getToken(), // Voucher lang: getLocalLocale(), // language Accept: 'application/json', // Accept the type of return data 'Content-Type': 'application/json; charset=utf-8', // Content format }; // 5. Request configuration const axiosConfig: AxiosRequestConfig = { method: _m, // Request method url, // Server address headers: { // Merge request header ...headers, ...( || {}), }, responseType, // Return value type }; // 6. Request configuration needs to be corrected for different request types if (data) { // For payloads, different request methods carry information different ways, so the difference is made here if (_m === 'get') { = data; } else if (data instanceof FormData) { = data; } else { = data; } } // Add a request interceptor ( // Placeholder (config: any) => { return config; }, // Failure will return failure (error: any) => { return (error); } ); // 7. Add a response interceptor ( // A successful callback, the parameter that initiated the request is passed back as the second parameter (res: any) => handleSuccess(res, params), // Failed callback, pass the parameter that initiated the request as the second parameter (err: any) => handleError(err, params) ); // 8. Constructing a callback function with successful request -- mainly to format the return data function handleSuccess(response: AxiosResponse<IResponse>, requestParams: RequestParams) { if () { // Deconstruct data const { code, msg, result } = ; if (code !== 0) { (msg); } return filter ? result?.data ?? result : ; } else { ('incorrect data format'); return ; } } // 9. Constructing a callback function that fails to request function handleError(err: AxiosError, requestParams: RequestParams) { if () { (`api: ${}: ${}`); } if (err instanceof Error) { if () { (); } } if (!) { // Handle network disconnection ('netwrok error'); } return (err); } // 10. Send the request and use the request result (Promise object) as the return value of the function return (axiosConfig); }; }); export default req;
This is the end of this article about the two methods of Vue encapsulating axios. For more related content on Vue encapsulating axios, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!