HTTP

fetch()

Send a request with explicit method, redirect and cancellation policies; inspect and consume its response. Local Node 22.16.0; production target compatibility pending. See https://nodejs.org/download/release/v22.16.0/docs/api/globals.html.

Formal Syntax & Structure

nodejs syntaxnodejs
fetch(input[, init])

Parameters & Attributes

NameTypeDescription
inputstring | URL | RequestRequest destination or request object.
initobjectRequest options, including signal.

Return Value

Promise<Response>

Result or receiver of the documented operation; see the linked versioned API contract.

Working Example

Example Snippetnodejs
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) {  const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler);  server.listen(0, '127.0.0.1');  await once(server, 'listening');  try { await use(`http://127.0.0.1:${server.address().port}`); }  finally {    await new Promise(resolve => {      server.close(resolve);      server.closeAllConnections();    });  }}const localFetch = (url, options = {}) => fetch(url, {  ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});await withServer((q,r)=>{r.statusCode=404;r.setHeader('content-type','application/json');r.end('{"error":"missing"}');},async base=>{const r=await localFetch(base);console.log(r.ok,r.status,(await r.json()).error);});
Node.js Reference