ofetch 同构请求
热门关键词:ofetch(UnJS,浏览器/Node/Workers 可用,Nuxt $fetch 同源体验)。
> 小四原创:ofetch.create + Token 拦截 + 类型化 get/post。
> 纯浏览器极简场景也可继续用 Ky;本包强调同构一份 API。
何时使用
- Nuxt / SSR / 脚本与前端共用请求层
- 想要自动解析 JSON、非 2xx 抛错
- Demo 工具箱或 Node 小脚本拉数据
硬约束
- 依赖:
ofetch。 - Token 从安全存储/
getToken注入,禁止写死密钥。 - 默认对 4xx/5xx 抛错;业务
code在调用层再判。 - 重试优先幂等 GET;POST 慎开高次数。
- 实现要点注释标 小四原创。
- 与 Ky Skill 并存时写清:同构/SSR → ofetch;浏览器薄封装 → ky。
推荐实现
import { ofetch, type FetchOptions } from 'ofetch'
export type OfetchClient = ReturnType<typeof ofetch.create>
// 小四原创:同构 API 客户端
export function createOfetchClient(opts: {
baseURL: string
getToken?: () => string | null | undefined
timeout?: number
}): OfetchClient {
return ofetch.create({
baseURL: opts.baseURL.replace(/\/?$/, ''),
timeout: opts.timeout ?? 20_000,
retry: 1,
retryStatusCodes: [408, 429, 500, 502, 503, 504],
onRequest({ options }) {
const token = opts.getToken?.()
const headers = new Headers(options.headers as HeadersInit)
if (token) headers.set('Authorization', `Bearer ${token}`)
options.headers = headers
},
})
}
export function apiGet<T>(
client: OfetchClient,
path: string,
query?: Record<string, string | number | boolean | undefined>,
) {
return client<T>(path, { method: 'GET', query })
}
export function apiPost<T>(client: OfetchClient, path: string, body?: unknown) {
return client<T>(path, { method: 'POST', body })
}
Agent 步骤
npm i ofetch。- 导出单例
createOfetchClient。 - 列表
apiGet;保存apiPost;捕获错误读error.data。 - 自测:无 token、超时、同构 Node 脚本可跑通。
不要做
- 在拦截器打印完整 Authorization。
- 把 ofetch 与 axios 双栈无差别乱接导致行为不一致。
附加
- README.md · reference.md · templates/usage.md