用户配置获取执行
可用作全球获取执行,也可用作本地获取执行,具体针对一揽子方案.
适配器
- @ fach- impl/ 交叉比对 - 使用( I) 横切 作为获取执行.
- @ fetch- impl/ playwright (英语) - 使用( I) 剧作家 浏览器作为获取执行 .
使用量
默认获取执行是 globalThis.fetch在几乎所有现代环境中(浏览器、节点.js、德诺、Cloudflare工人等)都行之有效.
import fetch from "@fetch-impl/fetcher";
// use fetch as usual
fetch("https://example.com").then(async (res) => {
console.log(res.status, await res.text());
});
您可以使用自定义的 fetcher.set数字 :
import fetch, { fetcher } from "@fetch-impl/fetcher";
// configure fetch to use a custom fetch implementation
fetcher.set(async (...args) => {
return new Response("Hello, World!", { status: 200 });
});
// use fetch as usual, but it will use the custom fetch implementation and always return "Hello, World!"
fetch("https://example.com").then(async (res) => {
console.log(res.status, await res.text());
});
如果您是软件包作者, 想要让用户配置抓取执行, 您可以使用 Fetcher 创建可配置本地抓取执行:
// add a fetch.ts file like this to your package
import { Fetcher } from "@fetch-impl/fetcher";
export const fetcher = new Fetcher();
export const fetch = (...args) => fetcher.fetch(...args);
export default fetch;
// and use your own fetch implementation like this
import fetch from "./fetch";
// use fetch as usual
export async function makeRequest(url: string): Promise<string> {
const res = await fetch(url);
return res.text();
}
// don't forget to re-export the fetcher instance so that your users can configure the fetch implementation
export * from "./fetch";
您的用户可以这样配置抓取执行 :
import { makeRequest, fetcher } from "your-package";
import { useCrossFetch } from "@fetch-impl/cross-fetch";
// user configure fetch to use a custom fetch implementation
useCrossFetch(fetcher);
// user use makeRequest as usual, but it will use the custom fetch implementation
makeRequest("https://example.com").then((text) => {
console.log(text);
});