SoFunction
Updated on 2025-04-07

Detailed explanation of the implementation of axios request response data encrypted and decrypted encapsulation

Installation dependencies

In front-end development, we often need to send requests to the back-end to obtain data. In order to ensure the security of the data, the request parameters need to be encrypted when sending the request. This article will introduce how to encapsulate request response data encryption and decryption using Typescript and Axios.

First we need to install the following dependencies:

  • Axios: Used to send requests
  • crypto-js: used to encrypt request parameters
npm install axios crypto-js
npm install axios

Encapsulation basic axios

Here is a basic Axios configuration, encapsulated using Typescript and Axios. It includes an interceptor for adding a common request header to each request. You can extend your request configuration on this basis.

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
const axiosInstance: AxiosInstance = ({
  baseURL: '</api>',
  timeout: 10000,
  withCredentials: true, // Cookies allowed});
((config: AxiosRequestConfig) => {
  ['Authorization'] = 'your-token';
  return config;
});
export default axiosInstance;

In this example, we create a name calledaxiosInstanceAxios instance, which has a common request headerAuthorization, the value isyour-token. You can modify and extend this basic configuration according to your needs.

For example, you could add an interceptor to add a timestamp to each request to ensure that the request is not cached:

((config: AxiosRequestConfig) => {
  ['Authorization'] = 'your-token';
  ['Cache-Control'] = 'no-cache';
  ['Pragma'] = 'no-cache';
  ['Expires'] = '0';
   = {
    ...,
    timestamp: new Date().getTime(),
  };
  return config;
});

In addition, you can also add error handling logic, timeout handling logic, etc. to this basic configuration to meet your specific needs.

Encapsulation encryption method

The encryption method can be encapsulated separately, which can be called more conveniently. The code is as follows:

import CryptoJS from 'crypto-js';
/**
  * Encrypt the data
  * @param data Encrypted data
  * @param key Encryption key
  * @returns Encrypted string
  */
export const encryptData = (data: any, key: string): string => {
  // Encrypt the data using the AES encryption method of the CryptoJS library  const ciphertext = (
    (data),
    .(key),
    {
      mode: ,
      padding: .Pkcs7,
    }
  );
  // Convert the encrypted result to a string and return  return ();
}

This method receives two parameters: the data that needs to be encrypted and the encryption key. It encrypts the data using the AES algorithm and returns the encrypted string.

Package decryption method

The decryption method can be encapsulated separately, which can be called more conveniently. The code is as follows:

import CryptoJS from 'crypto-js';
/**
  * Decrypt data
  * @param ciphertext
  * @param key Decryption key
  * @returns Decrypted data
  */
export const decryptData = <T>(ciphertext: string, key: string): T => {
  let decryptedData;
  try {
    // Use the AES decryption method of CryptoJS library to decrypt the data    const decryptedBytes = (
      ciphertext,
      .(key),
      {
        mode: ,
        padding: .Pkcs7,
      }
    );
    // Convert the decrypted result to a string and parse it into a JSON object    const decryptedString = (.Utf8);
    decryptedData = (decryptedString);
  } catch (error) {
    // If decryption fails, an error is thrown    throw new Error('Failed to decrypt data: ' + );
  }
  // Return the decrypted data  return decryptedData as T;
}

existdecryptDataAdd a generic to the function<T>, indicates the desired type of decrypted data. In the return statement of the function, convert the return value toTtype. In usedecryptDataWhen a function, you need to explicitly specify the desired return type, for example:const decryptedData: MyData = decryptData<MyData>(ciphertext, key);

Encapsulation request method

Next, encapsulate a request method, send the request using Axios and encrypt the request parameters before sending the request. The data returned in the background uses the same key as the encryption method, and the returned ciphertext data is stored inmiddle. Then, the ciphertext data is decrypted into a string using the AES decryption method of the CryptoJS library and parsed into a JSON object. The code is as follows:

import axios, { AxiosResponse, AxiosError } from 'axios';
import CryptoJS from 'crypto-js';
/**
  * Initiate an encrypted GET request
  * @param url Request address
  * @param params Request parameters
  * @param key Encryption key
  * @returns Returns the decrypted JSON object
  */
export const requestGet = async &lt;T&gt;(url: string, params: any, key: string): Promise&lt;T&gt; =&gt; {
  const encryptedParams = encryptData(params, key);
  try {
    const res = await (url, {
      params: {
        data: encryptedParams,
      },
    });
    if (!) {
      throw new Error('Response data is empty.');
    }
    return decryptData&lt;T&gt;(, key);
  } catch (error) {
    throw new Error('Failed to send request: ' + );
  }
};
/**
  * Initiate an encrypted POST request
  * @param url Request address
  * @param data Request parameters
  * @param key Encryption key
  * @returns Returns the decrypted JSON object
  */
export const requestPost = async &lt;T&gt;(url: string, data: any, key: string): Promise&lt;T&gt; =&gt; {
  const encryptedData = encryptData(data, key);
  try {
    const res = await (url, {
      data: encryptedData,
    });
    if (!) {
      throw new Error('Response data is empty.');
    }
    return decryptData&lt;T&gt;(, key);
  } catch (error) {
    throw new Error('Failed to send request: ' + );
  }
};

WillrequestGetandrequestPostThe return type of the method is defined asPromise<T>,inTIt is the decrypted data type. Explicitly specify the decrypted data type when calling these methods, e.g.const res = await requestGet<MyData>('</api/data>', params, 'my-secret-key');

requestGetThe method encapsulates a GET request,requestPostThe method encapsulates a POST request. The AES encryption and decryption methods of the CryptoJS library are used to process the request parameters and return data. When using these methods, you need to provide the encryption key and pass the request parameters as needed.

Detect whether the returned data is empty or invalid. If the data is empty or invalid, we will throw an error. Then use the AES decryption method to decrypt the returned data. If the decryption fails, an error will be thrown. Then, the decrypted data is parsed into a JSON object. If parsing fails, an error will be thrown. Finally, the decrypted JSON object is returned to the caller.

Use Packaging Method

We use the request method we encapsulated in the React component. The code is as follows:

import { request } from './request';
const App = () => {
  const handleGetData = async () => {
    try {
     const res = await requestPost('</api/data>', {
        username: 'user',
        password: 'pass',
      }, 'my-secret-key');
      ();
    } catch (error) {
      (error);
    }
  };
  return (
    <button onClick={handleGetData}>Get Data</button>
  );
}

In the above code, callrequestPostThe method sends a POST request, and the request parameters are{ username: 'user', password: 'pass' }. The encryption key passed ismy-secret-key. After the request is successful, the console will output the returned data. This encryption key can be encapsulated uniformly, and you don’t need to pass parameters every time you call it.

Ending

This article describes how to use Typescript and Axios to encapsulate a request encryption method in front-end development.

First, we installed the necessary dependencies: Axios and crypto-js. We then encapsulate a basic Axios configuration and add an interceptor to add a common request header to each request. Next, we encapsulate the encryption and decryption methods, and use the AES algorithm to encrypt and decrypt the request parameters and return data. Finally, we encapsulate a request method that uses Axios to send the request and encrypts the request parameters before sending the request. After the request is successful, the returned ciphertext data is decrypted into a string using the AES decryption method of the CryptoJS library and parsed into a JSON object.

If you need to send requests in front-end development and protect the security of data, you can refer to the methods used in this article for encryption and decryption processing.

The above is the detailed explanation of the implementation of axios request response data to be integrated and decrypted. For more information about encapsulating axios request response data, please pay attention to my other related articles!