npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@yubei826/http-client

v1.0.2

Published

A HTTP client library based on Axios

Readme

@yubei826/http-client

一个基于 Axios 封装的、功能强大的 TypeScript HTTP 客户端库,提供了开箱即用的请求/响应拦截、Token 管理、自动刷新、错误处理、请求取消等企业级特性。

特性

  • 🛠️ 类型安全:完全使用 TypeScript 编写,提供完整的类型定义。
  • 🔧 可配置化:支持全局配置,如基础URL、超时时间、请求头等。
  • 🔄 智能拦截器:内置请求/响应拦截器,支持身份认证、参数序列化、错误统一处理。
  • 🔐 Token 自动管理:支持访问令牌(Token)的自动注入与刷新机制。
  • ❌ 请求取消:支持取消单个请求或取消所有 pending 中的请求。
  • 📤 文件传输:内置文件上传(upload)和下载(download)的便捷方法。
  • 🧩 模块化设计:代码结构清晰,易于扩展自定义逻辑。

安装

# 使用 npm 安装
npm install @yubei826/http-client

# 或使用 yarn 安装
yarn add @yubei826/http-client

# 或使用 pnpm 安装
pnpm add @yubei826/http-client

注意:此库依赖 axios, qs, json-bigint,请确保您的项目中也安装了它们。

npm install axios qs json-bigint

快速开始### 1. 初始化

在应用的入口文件(如 main.ts 或 app.ts)中,初始化 HTTP 客户端。

import http from '@yubei826/http-client';

// 假设您有一个从 localStorage 或其他地方获取 token 的方法
const getToken = () => localStorage.getItem('access_token') || '';

http.init({
  baseURL: 'https://api.your-domain.com', // 你的 API 基础地址
  timeout: 10000, // 10秒超时
  getToken: () => getTokenInfo(), // 提供获取 Token 的函数
  // 统一的错误处理回调(例如使用 UI 组件的 Toast)
  onError: (msg) => {
    console.error(msg);
    // 例如: ElMessage.error(msg);
  },
  // Token 失效时的回调(例如跳转到登录页)
  onLogout: () => {
    console.warn('Token expired, logging out...');
    // 例如: router.push('/login');
  },
  // (可选)提供刷新 Token 的逻辑
  refreshToken: async (oldToken) => {
    const response = await http.postOriginal<{ token: string; refreshToken: string }>('/auth/refresh', { refreshToken: oldToken });
    return response.data; // 返回新的 token 和 refreshToken
  },
  // (可选)刷新 Token 成功后的回调,可用于保存新的 Token
  onRefreshTokenSuccess: (newToken, newRefreshToken) => {
    localStorage.setItem('access_token', newToken);
    localStorage.setItem('refresh_token', newRefreshToken);
  }
});

2. 发起请求

在您的组件或服务中,直接使用导入的 http 对象发起请求。

import http from '@yubei826/http-client';

// 获取用户列表 (GET)
const fetchUsers = async () => {
  try {
    const userList = await http.get<User[]>('/users');
    console.log('用户列表:', userList);
    return userList;
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
};

// 创建新用户 (POST)
const createUser = async (userData: CreateUserDto) => {
  try {
    const newUser = await http.post<User>('/users', userData);
    console.log('用户创建成功:', newUser);
    return newUser;
  } catch (error) {
    console.error('创建用户失败:', error);
  }
};

// 上传文件 (POST + multipart/form-data)
const uploadFile = async (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('remark', 'This is a file');

  try {
    const result = await http.upload<{ url: string }>('/upload', formData);
    console.log('文件上传成功,地址:', result.url);
  } catch (error) {
    console.error('文件上传失败:', error);
  }
};

配置项

HttpClientConfig 配置选项

| 参数名 | 类型 | 必填 | 默认值 | 描述 | |--------|------|------|--------|------| | baseURL | string | ✅ | '/api' | 所有请求的基础 URL | | timeout | number | ❌ | 30000 | 请求超时时间(毫秒) | | defaultHeaders | Record<string, string> | ❌ | { 'Content-Type': 'application/json' } | 默认的请求头 | | headersType | string | ❌ | 'application/json' | 默认的 Content-Type | | successCode | number | ❌ | 200 | 接口请求成功的业务状态码 | | transformRequestData | boolean | ❌ | false | 是否自动将对象转换为 multipart/form-data (FormData) | | getToken | () => string | ❌ | () => '' | 获取当前访问令牌的函数 | | refreshToken | (oldToken: string) => Promise<{ token: string; refreshToken: string }> | ❌ | 未实现 | 刷新令牌的函数。必须返回一个 Promise,解析出新的 token 和 refreshToken | | onError | (msg: string) => void | ❌ | (msg) => console.error(msg) | 统一错误处理函数,接收错误信息,通常用于显示 Toast 提示 | | onLogout | () => void | ❌ | () => console.warn(...) | Token 失效处理函数,通常用于跳转到登录页 | | onRefreshTokenSuccess | (newToken: string, newRefreshToken: string) => void | ❌ | - | 刷新 Token 成功后的回调,可用于保存新的 Tokens |

API 方法

HttpClient 对象提供以下方法:

常规请求

// 发起 GET 请求,返回解析后的响应数据 data 字段。
.get<T>(url: string, config?: RequestConfig): Promise<T>


// 发起 POST 请求,返回解析后的响应数据 data 字段。
.post<T, D = any>(url: string, data?: D, config?: RequestConfig<D>): Promise<T>

// 发起 POST 请求,返回完整的响应对象 ({ code, data, msg, success })。
.postOriginal<T, D = any>(url: string, data?: D, config?: RequestConfig<D>): Promise<IResponse<T>>

// 发起 PUT 请求。
.put<T, D = any>(url: string, data?: D, config?: RequestConfig<D>): Promise<T>

// 发起 DELETE 请求。
.delete<T>(url: string, config?: RequestConfig): Promise<T>

文件操作

// 发起文件下载请求(自动设置 responseType: 'blob')。
.download<T = Blob>(config: RequestConfig): Promise<T>

// 发起文件上传请求(自动设置 headersType: 'multipart/form-data')。
.upload<T = any, D = any>(config: RequestConfig<D>): Promise<T>

请求取消

// 取消一个或多个指定 URL 的请求。
.cancelRequest(url: string | string[]): void

// 取消所有正在进行的请求。
.cancelAllRequest(): void

高级用法

自定义请求配置

每个请求方法都接受一个可选的 RequestConfig 对象,它可以覆盖全局配置并添加特定于此请求的设置。

// 示例:发起一个不需要自动添加 Authorization 头的请求
await http.get('/public/data', {
  headers: {
    Authorization: '' // 覆盖全局的 Token 注入
  }
});

// 示例:发送 x-www-form-urlencoded 格式的数据
await http.post('/login', {
  username: 'admin',
  password: 'password'
}, {
  headersType: 'application/x-www-form-urlencoded'
});

// 示例:隐藏特定请求的错误提示
await http.get('/some/endpoint', {
  hideToast: true
});

处理大整数 (BigInt)

后端返回的 JSON 中如果包含大整数(如 Java 的 Long 类型),JavaScript 的 JSON.parse 会丢失精度。本库使用 json-bigint 库自动处理此问题,会将大数字转换为字符串,确保精度无损。

注意事项

  • Token 刷新:如需使用自动刷新 Token 功能,必须在初始化时配置 refreshToken 和 onRefreshTokenSuccess 回调。

  • 错误处理:onError 是全局错误回调,但可以通过在请求配置中设置 hideToast: true 来禁用单个请求的默认提示。

  • 请求取消:取消请求是基于 AbortController 实现的,取消后请求会进入 rejected 状态。

  • 依赖:请确保项目安装了正确的 peerDependencies (axios, qs, json-bigint)。

许可证

MIT License