Making HTTP Requests

1. Using http.get for GET Requests

Example

http.get("http://api/x", (res) => {
  let data = "";
  res.on("data", (c) => data += c).on("end", () => console.log(data));
});

2. Using http.request Method

OptionUse
methodHTTP verb
headersObject
agentConnection pool
signalAbortSignal
timeoutSocket idle ms

3. Using https.request for Secure Requests

Extra OptionsPurpose
caTrusted CAs
rejectUnauthorizedDefault true
servernameSNI

4. Using Native Fetch API (modern approach)

Example: Modern fetch v18+ stable

const res = await fetch("https://api.example.com/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Ada" }),
  signal: AbortSignal.timeout(5000)
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
PropertyUse
res.ok2xx indicator
res.json() / text() / blob() / arrayBuffer()Body parsers
res.bodyReadableStream

5. Setting Request Headers

HeaderUse
AuthorizationBearer <token>
User-AgentIdentify client
AcceptNegotiate content type
Content-TypeBody MIME
Accept-EncodingCompression negotiation

6. Sending Request Body

Body TypeNotes
String / BufferRaw
URLSearchParamsAuto sets x-www-form-urlencoded
FormDataAuto sets multipart boundary
ReadableStreamStreaming upload

7. Working with Query Parameters

Example

const u = new URL("https://api.example.com/search");
u.searchParams.set("q", "node");
const res = await fetch(u);

8. Handling Response Data

PatternUse
await res.json()Parsed JSON
await res.text()String
Stream large responsesfor await (const c of res.body)

9. Following Redirects Manually

OptionBehavior
redirect: "follow" (default)Auto-follow
redirect: "manual"Inspect 3xx response
redirect: "error"Throw on redirect

10. Setting Request Timeout

Example

const res = await fetch(url, { signal: AbortSignal.timeout(5_000) });

11. Using AbortController for Cancellation

Use CaseHow
User-initiated cancelCall controller.abort()
Combine signalsAbortSignal.any([s1, s2])

12. Handling Request Errors

ErrorMeaning
ECONNREFUSEDNo listener on port
ETIMEDOUTNo response in time
ENOTFOUNDDNS lookup failed
ECONNRESETPeer dropped connection
AbortErrorAborted via signal