From 2917f098764126d0956497b9fb67cc25a70d1829 Mon Sep 17 00:00:00 2001 From: Alessandro Miliucci Date: Wed, 2 Apr 2025 11:37:43 +0200 Subject: [PATCH] doc: improved fetch docs PR-URL: https://github.com/nodejs/node/pull/57296 Refs: https://undici.nodejs.org Reviewed-By: Matteo Collina Reviewed-By: Marco Ippolito Reviewed-By: James M Snell --- doc/api/globals.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/doc/api/globals.md b/doc/api/globals.md index d25b50d2b12..558e008f055 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -498,6 +498,46 @@ changes: A browser-compatible implementation of the [`fetch()`][] function. +```mjs +const res = await fetch('https://nodejs.org/api/documentation.json'); +if (res.ok) { + const data = await res.json(); + console.log(data); +} +``` + +The implementation is based upon [undici](https://undici.nodejs.org), an HTTP/1.1 client +written from scratch for Node.js. You can figure out which version of `undici` is bundled +in your Node.js process reading the `process.versions.undici` property. + +## Custom dispatcher + +You can use a custom dispatcher to dispatch requests passing it in fetch's options object. +The dispatcher must be compatible with `undici`'s +[`Dispatcher` class](https://undici.nodejs.org/#/docs/api/Dispatcher.md). + +```js +fetch(url, { dispatcher: new MyAgent() }); +``` + +It is possible to change the global dispatcher in Node.js installing `undici` and using +the `setGlobalDispatcher()` method. Calling this method will affect both `undici` and +Node.js. + +```mjs +import { setGlobalDispatcher } from 'undici'; +setGlobalDispatcher(new MyAgent()); +``` + +## Related classes + +The following globals are available to use with `fetch`: + +* [`FormData`](https://nodejs.org/api/globals.html#class-formdata) +* [`Headers`](https://nodejs.org/api/globals.html#class-headers) +* [`Request`](https://nodejs.org/api/globals.html#request) +* [`Response`](https://nodejs.org/api/globals.html#response). + ## Class: `File`