接口前缀
客户端级别的请求体,后续调用时传递相同参数会覆盖上去
特性:
// 用法1:直接发送请求
const res = await fetcher().get<Blog>("https://nickyzj.run:3030/blogs/hello-world");
// 用法2:创建实例
const api = fetcher("https://nickyzj.run:3030", { headers: { Authorization: "Bearer token" } });
const res = await api.get<Blog>("/blogs/hello-world", { headers: {...}, params: { page: 1 } }); // 与实例相同的 headers 会覆盖上去,params 会转成 ?page=1 跟到 url 后面
// 用法3:使用代理
const api = fetcher("https://api.example.com", {
proxy: "http://127.0.0.1:7890"
});
// 安全处理请求结果
const [error, data] = await to(api.get<Blog>("/blogs/hello-world"));
if (error) {
console.error(error);
return;
}
console.log(data);
// 缓存请求结果
const getBlogs = withCache(api.get);
await getBlogs("/blogs");
await sleep();
await getBlogs("/blogs"); // 不发请求,使用缓存
基于 Fetch API 的请求客户端