基于 Alova.js 封装的企业级 HTTP 请求库,提供统一响应结构、请求/响应拦截器、超时处理与 ACK 重试能力。
pnpm add @iap/http
import { createHttp } from '@iap/http'
const http = createHttp({ baseUrl: 'https://api.example.com' })
const res = await http.get<User[]>('/users')
console.log(res.data) // User[]
createHttp(instanceConfig?)创建一个 HTTP 实例,所有配置项均为可选。
const http = createHttp({
baseUrl: 'https://api.example.com',
timeout: 10_000,
headers: { 'X-App-Version': '1.0.0' },
onRequest: (config) => {
return { ...config, headers: { ...config.headers, Authorization: `Bearer ${token}` } }
},
onResponse: (res) => {
if (res.code !== 200) throw new Error(res.message)
return res
},
onError: (error, config) => {
console.error(`请求失败: ${config.url}`, error)
},
})
HttpInstanceConfig)| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
baseUrl |
string |
'' |
所有请求路径的前缀基地址 |
timeout |
number |
10000 |
默认超时时间(毫秒) |
headers |
Record<string, string> |
{} |
默认请求头,与每次请求头合并 |
onRequest |
RequestInterceptor |
— | 发送前执行的请求拦截器 |
onResponse |
ResponseInterceptor |
— | 成功响应后执行的响应拦截器 |
onError |
ErrorInterceptor |
— | 捕获未处理异常时执行的错误拦截器 |
http.get<T>(url, config?)
http.post<T>(url, body?, config?)
http.put<T>(url, body?, config?)
http.patch<T>(url, body?, config?)
http.delete<T>(url, config?)
http.request<T>(config) // 完整控制
所有方法均返回 Promise<HttpResponse<T>>。
HttpResponse<T>)interface HttpResponse<T = unknown> {
code: number // 200 表示成功,-1 表示错误/超时
message: string
data: T
timestamp: number
description: string
etag: string
status?: string // 'error' | 'timeout'(仅在失败时存在)
}
HttpConfig)| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
url |
string |
— | 请求路径(相对于 baseUrl) |
baseUrl |
string |
— | 覆盖实例级 baseUrl |
method |
HttpMethod |
'GET' |
HTTP 方法 |
headers |
object |
{} |
与实例级请求头合并 |
body |
unknown |
— | 请求体 |
timeout |
number |
10000 |
覆盖实例级超时时间 |
signal |
AbortSignal |
— | 用于手动取消请求 |
ackRetry |
boolean |
false |
是否开启超时 ACK 重试 |
ackRetryCount |
number |
3 |
最大重试次数 |
ackRetryTimeoutRatio |
number |
1.5 |
每次重试的超时倍数 |
请求超时时,ACK 重试会以逐步增大的超时时间自动重发请求,适用于响应较慢或网络不稳定的场景。
const res = await http.get('/slow-endpoint', {
timeout: 2000,
ackRetry: true,
ackRetryCount: 3, // 最多重试 3 次
ackRetryTimeoutRatio: 2, // 每次超时翻倍:2s → 4s → 8s → 16s
})
传入 AbortSignal 可手动取消进行中的请求:
const controller = new AbortController()
const res = http.get('/data', { signal: controller.signal })
// 取消请求:
controller.abort()
以下函数已导出,可在拦截器或自定义逻辑中使用:
import { createErrorResponse, createTimeoutResponse, isTimeoutError } from '@iap/http'
| 函数 | 说明 |
|---|---|
createErrorResponse(msg, desc?) |
构造标准错误 HttpResponse |
createTimeoutResponse(ms) |
构造标准超时 HttpResponse |
isTimeoutError(error) |
判断未知错误是否为超时错误 |
import type {
HttpConfig,
HttpInstance,
HttpInstanceConfig,
HttpMethod,
HttpResponse,
RequestInterceptor,
ResponseInterceptor,
ErrorInterceptor,
} from '@iap/http'