no
Java后端
·2025-09-06
Hello,大家好,这里是小nuo😎。 我今天打算分享一下我自己做的一个 Fetch 请求库,制作它的起因呢,是我自己在学习做项目的过程中发现很多的教程使用的都是 Axios 。但是 Next.js 框架是推荐基于 Fetch 请求的。Axios 则是基于 XMLHttpRequest 和 Promise 的 HTTP 客户端 。 但是基于原生 Fetch 比较麻烦,无法做到像 Axios 一样便捷方便。参考了 Axios 与 Ky ,小nuo基于 Fetch 封装了一个 HTTP 客户端 - Ceno 。 Github地址:https://github.com/leehainuo/ceno 用法 Ceno 的用法与 Axios 很像确又有所不同,不过放心。Ceno 很容易上手的: ``` typescript import ceno from 'ceno'; const BASEURL = 'localhost'; const PORT = 8000; const c = ceno.create({ prefixUrl: `${BASEURL}:${PORT}`, // -> axios的 baseURL timeout: 6000, throwHttpErrors: false, // 若不了解则先设为 false }); c.interceptors.use({ request: { onFulfilled: (req) => { console.log('请求拦截器生效....'); return req; }, }, response: { onFulfilled: (res) => { console.log('响应拦截器生效....'); return res; }, onRejected: (err) => { if (err.status === 401) { console.log('401 错误待处理....'); } throw err; }, }, }); ``` 这样便可处理大多数情况了。如何发送请求,来看如下代码: ``` typescript // -> Get 请求 'localhost:8000/api' const json = c.get('api').json() ``` 很好~ 🥰 更多请查看 Github 仓库 https://github.com/leehainuo/ceno/blob/main/readme.md 为什么选择 Ceno ? Ceno 面向现代浏览器,支持 Node.js、Deno、Bun 。✅ Ceno 比 Axios 更加的轻量,现代化。Ceno 的 Unpacked Size 仅 **101kB** 。✅ Ceno 拥有 TypeScript 支持,保证类型安全。✅ Ceno 基于现代化的 Fetch API ,同时做到了写法简洁优雅。✅ ``` typescript // fetch const response = await fetch('https://example.com', { method: 'POST', body: JSON.stringify({data: '🍰'}), headers: { 'content-type': 'application/json' } }); if (!response.ok) { throw new Error(`Fetch error: ${response.statusText}`); } const json = await response.json(); console.log(json); // ceno import ceno from 'ceno'; const json = await ceno.post('https://example.com', { json: {data: '🍰'} }).json(); console.log(json); ``` 总结 Ceno 的目的就是为了方便的使用 Fetch,做到简洁、轻量、优雅。 如果大家有好的建议和想法,欢迎随时再评论区反馈交流。 同时小nuo希望大家点点 start ⭐,多多鼓励与支持~
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP