You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js 18+内置fetch()能否设置全局dispatcher?

如何修改Node.js 18+内置fetch的全局Dispatcher

Node.js 18+内置的fetch基于undici实现,但并未将undici的setGlobalDispatcher直接暴露到公共API中,且单独安装的undici包与Node.js内置的undici实例相互独立,因此无法通过外部安装的setGlobalDispatcher修改内置fetch的全局Dispatcher。

以下是两种可行的解决方案:

1. 显式为每个fetch调用指定Dispatcher

这是最稳妥且符合公共API规范的方式,无需依赖内部或实验性特性:

import { Agent } from 'undici';

const customAgent = new Agent({ /* 配置项 */ });
const response = await fetch('https://example.com', {
  dispatcher: customAgent
});

2. 覆盖全局fetch为外部undici的实现

如果你希望统一管理全局Dispatcher,可以将全局的fetch替换为你自行安装的undici版本的fetch,之后就能用该版本的setGlobalDispatcher来控制全局行为:

import { Agent, fetch, setGlobalDispatcher } from 'undici';

// 覆盖全局fetch
globalThis.fetch = fetch;

// 设置全局Dispatcher
setGlobalDispatcher(new Agent({ /* 配置项 */ }));

// 后续所有fetch调用都会使用这个全局Dispatcher
const response = await fetch('https://example.com');

注意:避免使用内部API

虽然可以通过process.binding('undici')访问Node.js内置的undici实例,但这属于未公开的内部API,随时可能在Node.js的新版本中变更或移除,不建议在生产环境中使用。

内容的提问来源于stack exchange,提问作者steveluscher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:24:58