Skip to content

Fetch 请求 ​

ts
import { HttpClient, HttpError } from '@axewo/fin-core/http/fetch'

const api = new HttpClient({ baseURL: '/api/', timeoutMs: 10000 })
const controller = new AbortController()
const orders = await api.get<{ id: string }[]>('orders', {
  params: { page: 1, status: ['draft', 'posted'] },
  signal: controller.signal,
})

运行环境需要标准 fetch、Headers、AbortController;Node 18 及以上具备这些能力。服务端使用绝对 API 地址,或注入能解析相对地址的 fetch。

配置 ​

选项说明
baseURL实例 API 前缀
headers / headersProvider默认请求头、每次请求动态读取的头
timeoutMs默认 30000,0 关闭超时,覆盖动态头、钩子和响应读取
credentials默认 same-origin
allowCrossOrigin默认 false;跨域目标需显式允许
fetch可注入 fetch,用于运行环境适配和测试
beforeRequest发送前修改请求头或内容,取消信号和禁止重定向策略由客户端保护
onError错误通知;不延长请求,不替换原始错误

单次请求支持 params、headers、timeoutMs、signal、credentials、allowCrossOrigin、responseType。request 还支持 method 和 body。

params 支持 URLSearchParams 或对象;数组编码为同名重复参数,null、undefined 忽略。普通对象和数组请求体自动编码 JSON;FormData 由浏览器补充 boundary。

方法和返回值 ​

  • get(path, config?)、delete(path, config?)。
  • post(path, body?, config?)、put(path, body?, config?)、patch(path, body?, config?)。
  • request(path, config?)。

默认解析 JSON,可指定 text、blob、arrayBuffer。204、205 返回 undefined。泛型 T 表示实际响应体,客户端不继续解包业务 data,也不判断业务 code。

ts
try {
  await api.post('orders', { name: '新订单' })
} catch (error) {
  if (error instanceof HttpError) {
    // code: HTTP、NETWORK、TIMEOUT、ABORT、PARSE
    // HTTP 错误还具有 status、response;不要将原始异常直接展示或记录。
    if (error.code === 'ABORT') return
  }
  throw error
}

Fetch 的取消错误是 ABORT。安全错误适配见配置与错误。客户端不自动重试写请求,也不保存认证信息;使用动态认证与宿主票据时见认证请求。