Skip to content

HTTP 封装(Http)

提供轻量 fetch 封装与工具:超时、重试、查询字符串、FormData

使用指引(做什么、何时用)

  • 列表/搜索请求:用 Http.get(url, { query }) 拼接查询参数,避免手写 URL
  • 防卡死:请求可能卡住时,用 timeoutMs 自动超时;配合 UI 友好提示
  • 临时网络波动:用 retry: { times, delay } 做有限重试,提升成功率
  • 表单上传:用 toFormData(obj) 快速生成 FormData,对象值自动序列化
  • 任何 Promise:用 withTimeout(promise, ms) 给异步操作加超时保护
  • 统一错误:非 2xx 会抛错(含状态码),便于统一捕获

基本方法

  • Http.get/post/put/delete(url, options) 返回 JSON 或文本(根据 Content-Type
  • 选项:headersquerytimeoutMsretry: { times, delay }body
ts
import { Http } from 'nex-lib'
await Http.get('https://example.com/api', { query: { q: 'x' }, timeoutMs: 1000 })
json
{ "ok": true } // 示例,取决于接口

withQuery(url, params)

  • 将对象转为查询参数并拼接到 URL
  • 适合场景:分页、筛选、搜索关键字等
ts
import { withQuery } from 'nex-lib'
withQuery('https://a.com/path', { a: 1, b: true, c: null })
text
https://a.com/path?a=1&b=true

toFormData(obj)

  • 将对象转为 FormData,值为对象时自动 JSON 序列化
  • 适合场景:表单/文件上传、后端接收 multipart/form-data
ts
import { toFormData } from 'nex-lib'
const fd = toFormData({ a: 1, b: 'x', c: { k: 'v' } })
text
FormData(a=1, b=x, c={"k":"v"}) // 展示性输出,实际为原生 FormData

withTimeout(promise, ms)

  • 为任意 Promise 添加超时(抛出 Timeout 错误)
  • 适合场景:第三方接口或不稳定网络调用,防止长时间等待
ts
import { withTimeout } from 'nex-lib'
const p = new Promise(resolve => setTimeout(resolve, 50))
await withTimeout(p, 10)
text
Error: Timeout

withRetry(fn, times, delay)

  • 重试封装;与 ObjectUtils.retry 一致
  • 适合场景:偶发失败的请求(如网络抖动),但不适用于权限错误/参数错误

提示

  • 超时与重试可同时使用,先在单次请求上应用 timeoutMs,再用 retry 包裹整体调用。
  • 重试不应用于“必然失败”的情况(例如 400/401 参数或权限错误)。
ts
import { withQuery, toFormData, withTimeout, withRetry } from 'nex-lib'
withQuery('https://a.com', { a: 1, b: true })
const fd = toFormData({ a: 1 })
await withRetry(async () => 'ok', 3, 50)
text
https://a.com/?a=1&b=true
[FormData]
ok

Released under the ISC License.