一个基于 Axios 的强大 HTTP 客户端库,提供请求重试、自动取消重复请求、拦截器管理等高级功能。
🌍 Multi-language Support: 中文 | English
- 🚀 基于 Axios: 继承 Axios 的所有功能和 API
- 🔄 自动重试: 支持配置重试次数和延迟时间
- ⚡ 请求去重: 自动取消重复的请求
- 🎯 拦截器管理: 灵活的请求和响应拦截器
- 🛑 请求取消: 支持单个或批量取消请求
- 📦 单例模式: 全局统一的 HTTP 客户端实例
- 🔧 TypeScript: 完整的类型定义支持
- 🧪 高测试覆盖率: 92.71% 的测试覆盖率
# npm
npm install @lenqwang/http-client
# yarn
yarn add @lenqwang/http-client
# pnpm
pnpm add @lenqwang/http-clientimport httpClient from '@lenqwang/http-client';
// GET 请求
const response = await httpClient.get('/api/users');
console.log(response.data);
// POST 请求
const user = await httpClient.post('/api/users', {
name: 'John Doe',
email: 'john@example.com'
});
// PUT 请求
const updatedUser = await httpClient.put('/api/users/1', {
name: 'Jane Doe'
});
// DELETE 请求
await httpClient.delete('/api/users/1');import { HttpClient } from '@lenqwang/http-client';
const apiClient = HttpClient.getInstance({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Authorization': 'Bearer your-token'
}
});// 配置重试参数
const response = await httpClient.request({
url: '/api/data',
method: 'GET',
retryCount: 3, // 重试 3 次
retryDelay: 1000 // 每次重试延迟 1 秒
});// 相同的请求会自动取消前一个
const request1 = httpClient.get('/api/users');
const request2 = httpClient.get('/api/users'); // 会取消 request1
// 使用自定义请求键
const request3 = httpClient.get('/api/users', {
requestKey: 'get-users-list'
});// 取消特定请求
const request = httpClient.get('/api/data', {
requestKey: 'my-request'
});
httpClient.cancelRequest('my-request');
// 取消所有请求
httpClient.cancelAllRequests();// 跳过默认的响应处理逻辑
const response = await httpClient.get('/api/raw-data', {
skipResponseInterceptor: true
});const requestInterceptorIds = httpClient.addRequestInterceptor({
onFulfilled: (config) => {
// 添加认证头
config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
onRejected: (error) => {
console.error('Request error:', error);
return Promise.reject(error);
}
});const responseInterceptorIds = httpClient.addResponseInterceptor({
onFulfilled: (response) => {
// 处理响应数据
if (response.data.code === 200) {
return response;
}
throw new Error(response.data.message);
},
onRejected: (error) => {
// 处理错误响应
if (error.response?.status === 401) {
// 重定向到登录页
window.location.href = '/login';
}
return Promise.reject(error);
}
});// 移除请求拦截器
httpClient.removeRequestInterceptor(...requestInterceptorIds);
// 移除响应拦截器
httpClient.removeResponseInterceptor(...responseInterceptorIds);getInstance(config?: CustomRequestConfig): HttpClientInstance- 获取 HttpClient 单例实例
-
addRequestInterceptor(...interceptors: RequestInterceptor[]): number[]- 添加请求拦截器,返回拦截器 ID 数组
-
addResponseInterceptor(...interceptors: ResponseInterceptor[]): number[]- 添加响应拦截器,返回拦截器 ID 数组
-
removeRequestInterceptor(...interceptorIds: number[]): void- 移除指定的请求拦截器
-
removeResponseInterceptor(...interceptorIds: number[]): void- 移除指定的响应拦截器
-
cancelRequest(requestKey: string): void- 取消指定的请求
-
cancelAllRequests(): void- 取消所有进行中的请求
-
getRawAxios(): AxiosInstance- 获取原始的 Axios 实例
interface CustomRequestConfig<D = any> extends AxiosRequestConfig<D> {
skipResponseInterceptor?: boolean; // 是否跳过响应拦截器
retryCount?: number; // 请求重试次数
retryDelay?: number; // 请求重试延迟(毫秒)
requestKey?: string; // 请求唯一标识
}interface ResponseBody<T = any> {
code: number; // 响应状态码
data: T; // 响应数据
message: string; // 响应消息
}- 自动为每个请求生成唯一的
requestKey(格式:${method}-${url}) - 自动取消相同
requestKey的重复请求 - 为每个请求添加
AbortController信号
- 检查响应数据的
code字段,如果不等于 200 则抛出错误 - 自动清理已完成请求的
requestKey - 支持跳过拦截器处理(
skipResponseInterceptor: true)
- 自动处理 Axios 取消错误
- 支持请求重试机制
- 重试时会递减
retryCount并等待retryDelay时间
# 运行测试
npm test
# 运行测试并生成覆盖率报告
npm run test:coverage当前测试覆盖率:92.71%
# 安装依赖
pnpm install
# 开发模式(监听文件变化)
npm run dev
# 构建
npm run build
# 发布
npm run releaseMIT License - 详见 LICENSE 文件
欢迎提交 Issue 和 Pull Request!
如果您在使用过程中遇到问题,请:
Made with ❤️ by LenqWang