Skip to content

参考

ofetch 常用 API、选项、拦截器与 FetchError 字段速查。版本基线 ofetch 1.x

一、导入

写法说明
import { ofetch } from 'ofetch'增强实例(具名导出)
import { $fetch } from 'ofetch'同一实例的别名
import { FetchError } from 'ofetch'错误类(可用于 instanceof
import { createFetch } from 'ofetch'工厂函数,自定义底层 fetch/Headers
import { fetch } from 'ofetch'原生 fetch 的 polyfill(增强版)
import { ofetch } from 'ofetch/node'Node 专用子入口(undici 适配)

二、调用方式

API返回说明
ofetch(url, opts?)Promise<data>自动解析后的数据
ofetch.raw(url, opts?)Promise<FetchResponse>完整响应,数据在 _data
ofetch.native(...)Promise<Response>底层原生 fetch,无任何增强
ofetch.create(defaults, global?)$Fetch带默认值的新实例

三、常用选项(FetchOptions)

选项类型说明
methodstringHTTP 方法
bodyobject / string / FormData / Stream…可序列化对象自动 JSON 化
queryRecord<string, any>查询参数(ufo 拼接、合并)
paramsRecord<string, any>query已废弃别名
headersHeadersInit请求头
baseURLstring基础 URL(ufo 拼接)
responseTypejson|text|blob|arrayBuffer|stream解析方式,默认按 content-type
parseResponse(text) => any自定义解析函数(替换 destr)
ignoreResponseErrorboolean非 2xx 也不抛错
timeoutnumber超时(毫秒),内部用 AbortController
retrynumber | false重试次数;默认 GET=1,写方法=0
retryDelaynumber | (ctx) => number重试间隔(毫秒),可指数退避
retryStatusCodesnumber[]触发重试的状态码
signalAbortSignal手动中断
dispatcherundici.DispatcherNode≥18 走 undici 时(代理/连接池)
agentunknown老 Node(node-fetch-native)代理
duplex'half'流式 body,通常自动设置

四、retry 默认值

默认
retry(GET/HEAD 等读方法)1
retry(POST/PUT/PATCH/DELETE)0(防重复提交)
retryStatusCodes[408, 409, 425, 429, 500, 502, 503, 504]
retryDelay0

显式给 retry: n 后,所有方法都按 n 次(不再区分读写)。

五、拦截器(FetchHooks)

钩子触发时机context 关键字段
onRequest请求发出前request, options
onRequestError请求未拿到响应(网络层失败)request, options, error
onResponse收到响应并解析后request, response, options
onResponseError响应状态非 2xxrequest, response, options
  • 每个钩子都支持单个函数或函数数组MaybeArray)。
  • create 默认拦截器与单次调用拦截器会合并为数组依次执行(非覆盖)。
  • onRequestoptions.headers 已是 Headers 实例,改头用 .set()
  • 解析后的数据在 context.response._data

六、FetchError 字段

字段含义
message形如 [GET] "/x": 404 Not Found
data解析后的错误响应体
status / statusCode状态码(同值,兼容双命名)
statusText / statusMessage状态文本(同值)
response原始 FetchResponse(数据在 _data
request请求 URL/Request
options本次请求选项
cause底层原始错误

七、responseType ⇄ 返回类型

responseTypeTS 返回类型用途
json(默认)泛型 TJSON 数据
textstring纯文本
blobBlob二进制下载
arrayBufferArrayBuffer二进制缓冲
streamReadableStream流式(含 SSE text/event-stream

八、content-type 自动识别(detectResponseType)

响应 content-type识别为
application/...jsonjson
text/event-streamstream
text/*image/svgapplication/xml/xhtml/htmltext
其它blob

九、运行时依赖

依赖作用
destr安全 JSON 解析(失败不抛错)
node-fetch-native同构 fetch / 老 Node polyfill
ufoURL 工具(withBase 拼 baseURL、withQuery 合并 query)

API 查完,进 指南 · 基础 理解拦截器与重试机制,或 指南 · 进阶 看 create 分层、流式、自定义解析与迁移实战。