zs-axios-encrypt
v1.0.9
Published
axios封装 GET POST 加密 鉴权
Readme
HTTP 请求封装类
项目概述
本项目是一个基于 axios 的 HTTP 请求封装类,提供了请求拦截、响应拦截、参数加密等功能。通过集成 CryptoJS 实现了 AES 加密,确保数据传输的安全性。适用于需要统一 管理 HTTP 请求和加密处理的场景。
关键特性
- 基于
axios的轻量级封装 - 支持 GET 和 POST 请求
- 自动携带
Authorization头(Bearer Token) - 请求参数自动 AES 加密(CBC 模式,PKCS7 填充)
- 可自定义请求和响应拦截器
- 支持自定义配置(AES 密钥等)
- 在
axiosConfig配置项,允许直接传递 axios 原生配置(如baseURL、timeout等)
前置条件
- Node.js 环境
axios和crypto-js依赖
安装依赖
npm install axios crypto-js运行方法
导入
Request类:import Request from "./src/index.js";初始化
Request实例:const request = new Request({ token: "your_token_here", aesKey: "your_aes_key", aesIv: "your_aes_iv", axiosConfig: { // 这里可以传递 axios 的原生配置 baseURL: "https://api.example.com", headers: { 'Content-Type': 'application/json', }, withCredentials: true, }, });发起请求:
// GET 请求 request.get("/endpoint", { param1: "value1" }).then(response => { console.log(response.data); }); // POST 请求 request.post("/endpoint", { param1: "value1" }).then(response => { console.log(response.data); });
构建方法
本项目为纯 JavaScript 模块,无需构建步骤。直接导入即可使用。
配置说明
| 参数 | 类型 | 默认值 | 描述 |
|------------|--------|----------------------|--------------------------|
| axiosConfig | Object | - | axios 原生配置对象,可直接传递 axios 支持的所有配置项 |
| aesKey | String | "1234567890123456" | AES 加密密钥 |
| aesIv | String | "1234567890123456" | AES 初始化向量 |
| token | String | - | 认证 Token |
| requestInterceptor | Object | - | 请求拦截器(errorHandler) |
| responseInterceptor | Object | - | 响应拦截器(successHandler、errorHandler) |
许可证
本项目采用 MIT 许可证。详见 LICENSE 文件。
其他说明
- 加密功能默认对所有 GET 和 POST 请求生效。
- 如需自定义加密逻辑,可重写
encrypt方法。 - 响应拦截器需通过
responseInterceptor配置传入。 axiosConfig配置项允许直接传递 axios 原生配置,方便用户自定义请求行为。
示例
const request = new Request({
token: "your_token_here",
aesKey: "your_aes_key",
aesIv: "your_aes_iv",
axiosConfig: {
baseURL: "https://api.example.com",
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
},
responseInterceptor: {
successHandler: (response) => {
console.log("请求成功:", response.data);
return response.data;
},
errorHandler: (error) => {
console.error("请求失败:", error);
return Promise.reject(error);
},
},
});
request.post("/login", { username: "admin", password: "123456" });如有问题或建议,欢迎提交 Issue 或 Pull Request!
