增加nodejs内置fetch API的超时时间

rad*_*n04 8 node.js fetch-api

我正在使用 NodeJS 18 中引入的 Fetch API 来访问 API。但是,请求总是在 10 秒后超时,并显示以下错误消息。

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11576:11)
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:8522:28)
      at node:internal/deps/undici/undici:8480:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:8509:37)
      at processImmediate (node:internal/timers:478:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}
Run Code Online (Sandbox Code Playgroud)

我想增加获取请求超时之前的时间,但是我无法找到使用内置 NodeJS API 执行此操作的方法。

小智 3

我使用 Node 18 和 fetch api 遇到了同样的问题,并且我能够增加连接超时,如https://github.com/nodejs/undici/issues/1531#issuecomment-1178869993所示 ,我必须使用 npm 添加 undici :

npm install undici
Run Code Online (Sandbox Code Playgroud)

然后我可以从 undici 导入 setGlobalDispatcher、fetch 和 Agent:

import { fetch, setGlobalDispatcher, Agent} from 'undici';
Run Code Online (Sandbox Code Playgroud)

然后我在模块顶部的任何函数之前全局使用 setGlobalDispatcher,如下所示:

setGlobalDispatcher(new Agent({connect: { timeout: 20_000 }}));
Run Code Online (Sandbox Code Playgroud)

此后,一切正常,10 秒的连接超时已正确增加到 20 秒。

请注意,在我的例子中,我还使用了更新的“fetchWithTimeout”方法,而不是仅仅简单的 fetch 来满足请求超时。如果您还需要处理请求超时,您可以在Fetch API request timeout?找到一些实现。