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
| Option | Use |
|---|---|
method | HTTP verb |
headers | Object |
agent | Connection pool |
signal | AbortSignal |
timeout | Socket idle ms |
3. Using https.request for Secure Requests
| Extra Options | Purpose |
|---|---|
ca | Trusted CAs |
rejectUnauthorized | Default true |
servername | SNI |
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();
| Property | Use |
|---|---|
res.ok | 2xx indicator |
res.json() / text() / blob() / arrayBuffer() | Body parsers |
res.body | ReadableStream |
5. Setting Request Headers
| Header | Use |
|---|---|
Authorization | Bearer <token> |
User-Agent | Identify client |
Accept | Negotiate content type |
Content-Type | Body MIME |
Accept-Encoding | Compression negotiation |
6. Sending Request Body
| Body Type | Notes |
|---|---|
| String / Buffer | Raw |
| URLSearchParams | Auto sets x-www-form-urlencoded |
| FormData | Auto sets multipart boundary |
| ReadableStream | Streaming 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
| Pattern | Use |
|---|---|
await res.json() | Parsed JSON |
await res.text() | String |
| Stream large responses | for await (const c of res.body) |
9. Following Redirects Manually
| Option | Behavior |
|---|---|
redirect: "follow" (default) | Auto-follow |
redirect: "manual" | Inspect 3xx response |
redirect: "error" | Throw on redirect |
10. Setting Request Timeout
11. Using AbortController for Cancellation
| Use Case | How |
|---|---|
| User-initiated cancel | Call controller.abort() |
| Combine signals | AbortSignal.any([s1, s2]) |
12. Handling Request Errors
| Error | Meaning |
|---|---|
ECONNREFUSED | No listener on port |
ETIMEDOUT | No response in time |
ENOTFOUND | DNS lookup failed |
ECONNRESET | Peer dropped connection |
AbortError | Aborted via signal |