@geektech/backone-utils
HTTP 客户端
fetch 封装:超时、指数退避重试、查询参数与 JSON。
http 模块是基于 fetch 的轻量封装:超时、指数退避重试、请求 / 响应头合并、JSON 自动序列化与解析,零运行时依赖。
创建客户端
ts
import { createHttpClient } from '@geektech/backone-utils';
const api = createHttpClient({
baseUrl: 'https://api.example.com',
timeoutMs: 5_000,
retry: { maxRetries: 3, baseDelayMs: 100 },
});发起请求
ts
const { data } = await api.get<{ total: number }>('/stats', { query: { year: 2026 } });
const { data: created } = await api.post('/users', { body: { name: 'alice' } });
const res = await api.request('/upload', { method: 'PUT', body: formData });响应结构
| 字段 | 说明 |
|---|---|
status / ok | 状态码 / 是否 2xx |
headers | 响应头 |
data | 解析后的 JSON(非 JSON 响应则原样为文本) |
text | 原始文本 |
url | 最终请求 URL |
请求选项
| 选项 | 说明 |
|---|---|
query | 查询参数,自动拼接(undefined 值跳过) |
headers | 请求头(覆盖默认头) |
timeoutMs | 超时毫秒(覆盖客户端默认) |
retry | 重试配置;传 false 关闭本次重试 |
body | 对象自动 JSON 序列化,字符串原样发送 |
signal | 外部取消信号(与超时信号合并) |
重试配置
| 选项 | 默认 | 说明 |
|---|---|---|
maxRetries | 2 | 最大重试次数(额外的请求次数) |
baseDelayMs | 200 | 基础退避毫秒(指数退避:baseDelay * 2^attempt) |
retryableStatuses | 408/429/500/502/503/504 | 可重试的响应状态码 |
retryOnNetworkError | true | 是否重试网络错误与超时 |