GeezerVison is showing github.com — doc: improved fetch docs · nodejs/node@27b113d
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/globals.md +40Lines changed: 40 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -561,6 +561,46 @@ changes: |
561 | 561 |
|
562 | 562 | A browser-compatible implementation of the [`fetch()`][] function. |
563 | 563 |
|
| 564 | +```mjs |
| 565 | +const res = await fetch('https://nodejs.org/api/documentation.json'); |
| 566 | +if (res.ok) { |
| 567 | + const data = await res.json(); |
| 568 | + console.log(data); |
| 569 | +} |
| 570 | +``` |
| 571 | + |
| 572 | +The implementation is based upon [undici](https://undici.nodejs.org), an HTTP/1.1 client |
| 573 | +written from scratch for Node.js. You can figure out which version of `undici` is bundled |
| 574 | +in your Node.js process reading the `process.versions.undici` property. |
| 575 | + |
| 576 | +## Custom dispatcher |
| 577 | + |
| 578 | +You can use a custom dispatcher to dispatch requests passing it in fetch's options object. |
| 579 | +The dispatcher must be compatible with `undici`'s |
| 580 | +[`Dispatcher` class](https://undici.nodejs.org/#/docs/api/Dispatcher.md). |
| 581 | + |
| 582 | +```js |
| 583 | +fetch(url, { dispatcher: new MyAgent() }); |
| 584 | +``` |
| 585 | + |
| 586 | +It is possible to change the global dispatcher in Node.js installing `undici` and using |
| 587 | +the `setGlobalDispatcher()` method. Calling this method will affect both `undici` and |
| 588 | +Node.js. |
| 589 | + |
| 590 | +```mjs |
| 591 | +import { setGlobalDispatcher } from 'undici'; |
| 592 | +setGlobalDispatcher(new MyAgent()); |
| 593 | +``` |
| 594 | + |
| 595 | +## Related classes |
| 596 | + |
| 597 | +The following globals are available to use with `fetch`: |
| 598 | + |
| 599 | +* [`FormData`](https://nodejs.org/api/globals.html#class-formdata) |
| 600 | +* [`Headers`](https://nodejs.org/api/globals.html#class-headers) |
| 601 | +* [`Request`](https://nodejs.org/api/globals.html#request) |
| 602 | +* [`Response`](https://nodejs.org/api/globals.html#response). |
| 603 | + |
564 | 604 | ## Class: `File` |
565 | 605 |
|
566 | 606 | <!-- YAML |
|