Node-Fetch brings the Web Fetch API to Node.js, providing a familiar interface for making HTTP requests in a Node.js environment. The current stable version is 3.3.2. Both the v3 (ESM-only) and v2 (CommonJS) branches are actively maintained, receiving regular bug fixes and occasional new features.
npm install node-fetchVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to make a basic GET request to an external API and parse the JSON response. It also includes error handling for network issues and non-OK HTTP statuses.
Use `import fetch from 'node-fetch';` in an ESM context (e.g., in a `.mjs` file or a project with `"type": "module"` in `package.json`). For CommonJS, use `const fetch = await import('node-fetch');` (dynamic import) or stick to `node-fetch@2.x`.After awaiting `fetch`, always check `if (!response.ok) { throw new Error(...) }` before trying to read the body.Store the result of `response.json()` or `response.text()` in a variable if you need to access the body content multiple times, or use `response.clone()` before consuming it.
Use an `AbortController` to implement request timeouts. Create a controller, set a timeout, and pass the `signal` to the fetch options: `fetch(url, { signal: controller.signal })`.Ensure your project's Node.js version is `16.0.0` or higher. Update your `package.json`'s `engines` field accordingly.
Change `const fetch = require('node-fetch');` to `import fetch from 'node-fetch';`. Ensure your `package.json` has `"type": "module"` or use `.mjs` file extension.Provide a full, absolute URL (e.g., `https://example.com/api/data`) or construct one using `new URL(relativePath, baseUrl)` before passing it to `fetch`.
Verify that the target server is running and accessible at the specified URL and port. Check firewall rules or proxy settings if applicable.
Store the result of the first body consumption (e.g., `const data = await response.json();`) into a variable. If you need to read the body in multiple formats or multiple times, use `const clonedResponse = response.clone();` before the first consumption.
This is often an expected error for timeouts. Catch `AbortError` specifically (e.g., `if (error instanceof AbortError) { console.log('Request timed out'); }`) to handle it gracefully without crashing your application.No dependency data recorded yet.