如何延长Node.js内置Fetch API的请求超时时间?
解决Node.js 18 Fetch API连接超时问题
问题分析
你遇到的UND_ERR_CONNECT_TIMEOUT错误,是因为Node.js 18内置的Fetch API基于undici实现,默认连接超时时间为10秒。Fetch标准API本身没有提供直接设置超时的参数,但可以通过以下两种方式实现超时延长:
方法1:使用AbortController手动控制超时
这是标准Fetch API的通用解决方案,无需修改全局配置,灵活性高:
const fetchWithTimeout = async (url, options = {}, timeout = 30000) => { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); try { const response = await fetch(url, { ...options, signal: controller.signal }); clearTimeout(timeoutId); return response; } catch (error) { if (error.name === 'AbortError') { throw new Error('请求超时'); } throw error; } }; // 使用示例:设置30秒超时 fetchWithTimeout('https://your-external-api.com', {}, 30000) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
方法2:修改undici的全局超时配置
如果需要全局调整所有Fetch请求的连接超时,可以直接配置undici的参数(Node.js的Fetch底层依赖undici):
import { setGlobalDispatcher, Agent } from 'undici'; // 设置全局Agent,将连接超时改为30秒(单位:毫秒) setGlobalDispatcher(new Agent({ connectTimeout: 30000 })); // 之后的Fetch请求都会使用这个超时配置 fetch('https://your-external-api.com') .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
注意:这种方式会影响所有使用全局Dispatcher的请求,适合需要统一超时策略的场景。
额外说明
- 连接超时(connectTimeout)是指建立TCP连接的时间限制,和请求响应超时是不同概念。如果需要限制整个请求的总时长,方法1的AbortController方式更合适,因为它会覆盖从连接到响应的整个过程。
- 若外部接口本身响应缓慢,除了延长超时,也建议检查接口性能或考虑异步处理逻辑。
内容的提问来源于stack exchange,提问作者radostin04
相关产品推荐
相关产品推荐

