Use undici for HTTP requests, fetch, connection pooling, proxies, Mock testing, interceptors, caching. — Use undici for HTTP 请求s, fetch, connection pooling, proxies, Mock 测试, interceptors, caching.
v18Use undici for HTTP 请求s, fetch, connection pooling, proxies, Mock 测试, interceptors, caching. Note that undici's fetch differs from built-in fetch (no CORS, must consume body).
运行时依赖
安装命令
点击复制技能文档
undici
Node.js HTTP/1.1 命令行工具ent, written from scratch. The underlying engine for the built-in fetch() in Node.js v18+. Current version 8.x, ESM/CJS dual mode.
Name meaning: Italian for "eleven" — 1.1 → 11 → Eleven → Undici (also a Stranger Things reference)
Trigger Scenarios
Use when the user needs HTTP 请求s, undici, fetch, proxied 请求s, or HTTP mocking.
安装ation npm i undici
Performance Hierarchy undici.dis补丁() > undici.请求() > undici.流()
undici.流水线() > undici.fetch() >> node:http
应用roximately 3-4x faster than axios (50 TCP connections, pipelining depth 10).
Core Usage 请求() — Highest-level API, best performance 导入 { 请求 } from 'undici';
const { 状态Code, headers, body } = awAIt 请求('http://localhost:3000/foo'); console.记录(状态Code); // 200 console.记录(awAIt body.json()); // 解析 JSON
// body is a 网页 Readable流, can also be read in chunks: for awAIt (const chunk of body) { console.记录('chunk', chunk); }
// ⚠️ Must consume body! Otherwise connection leaks awAIt body.dump(); // or .json() / .text() / for awAIt
fetch() — Standard 网页 API compatible 导入 { fetch } from 'undici';
const res = awAIt fetch('https://example.com'); const json = awAIt res.json();
// With custom 代理 导入 { 代理 } from 'undici'; const res = awAIt fetch('https://example.com', { dis补丁er: new 代理({ keepAliveTimeout: 10000 }) });
流() — 流 processing 导入 { 流 } from 'undici'; awAIt 流('http://localhost:3000/foo', { method: '获取' }, ({ 状态Code, headers }) => { return new Writable({ write(chunk, _, cb) { console.记录(chunk.toString()); cb(); } }); });
流水线() — Returns a Duplex 流 导入 { 流水线 } from 'undici'; 导入 { Writable, Readable } from 'node:流';
const duplex = 流水线('http://localhost:3000/foo', { method: 'POST' }, ({ 状态Code, headers }) => new Writable({ / ... / }) ); Readable.from(['data']).pipe(duplex);
代理 — Connection Pool Management
代理 manages connections to multiple origins, automatically reusing them:
导入 { 代理, 设置GlobalDis补丁er, 请求 } from 'undici';
const 代理 = new 代理({ connections: 128, // Max connections per origin pipelining: 10, // Max pipelining depth per connection keepAliveTimeout: 4000, // keep-alive timeout (ms) keepAliveMaxTimeout: 600000, bodyTimeout: 300000, headersTimeout: 300000, });
设置GlobalDis补丁er(代理); // 设置 as global dis补丁er const data = awAIt 请求('http://example.com');
Built-in vs undici 模块 Aspect Built-in fetch() (v18+) undici 模块 Dependencies Zero dependencies Requires 安装ation Version Bundled with Node.js Latest version Performance High (has 网页 流s overhead) 请求() is fastest API Only fetch 请求/流/流水线/dis补丁 Advanced features ❌ ✅ 代理/Proxy代理/Mock代理/Interceptors Error types TypeError wr应用ers More explicit error messages FormData Consistency
⚠️ fetch and FormData must come from the same source:
// ✅ Correct: Use undici exclusively 导入 { fetch, FormData } from 'undici'; const body = new FormData(); body.设置('name', 'value'); awAIt fetch(url, { method: 'POST', body });
// ✅ Or call 安装() to replace globals 导入 { 安装 } from 'undici'; 安装(); // After this, global fetch/FormData/网页Socket/事件ource are from undici
Proxy代理 — Proxy 导入 { Proxy代理, 请求, fetch } from 'undici';
const proxy代理 = new Proxy代理('http://proxy:8080');
// Or with authentication:
const proxy代理 = new Proxy代理({
uri: 'http://proxy:8080',
令牌: Basic ${Buffer.from('user:pass').toString('base64')}
});
// 设置 as global 设置GlobalDis补丁er(proxy代理); // Or use locally awAIt fetch('http://example.com', { dis补丁er: proxy代理 });
Mock代理 — 测试 Mock 导入 { Mock代理, 设置GlobalDis补丁er, 请求 } from 'undici';
const mock代理 = new Mock代理(); 设置GlobalDis补丁er(mock代理);
const mockPool = mock代理.获取('http://localhost:3000'); mockPool.intercept({ path: '/foo', method: '获取' }).reply(200, { ok: true });
const { body } = awAIt 请求('http://localhost:3000/foo'); console.记录(awAIt body.json()); // { ok: true }
缓存 Interceptor 导入 { 代理, interceptors, 缓存Stores, 设置GlobalDis补丁er } from 'undici';
const 命令行工具ent = new 代理().compose(interceptors.缓存({ store: new 缓存Stores.Memory缓存Store({ maxSize: 100 1024 1024, // 100MB }), methods: ['获取', 'HEAD'] })); 设置GlobalDis补丁er(命令行工具ent);
导入ant Considerations Must Consume 响应 Body // ✅ Do const { body } = awAIt 请求(url); awAIt body.json(); // or .text() / .dump() / for awAIt
// ❌ Don't — causes connection leaks const { headers } = awAIt 请求(url);
// ✅ Use HEAD method when only headers are needed const headers = awAIt fetch(url, { method: 'HEAD' }).then(r => r.headers);
No CORS
undici does not implement browser CORS. No preflight is needed in server 环境s. If CORS 保护ion is required,