Make HTTP requests using only Node.js built-in modules. Supports all standard
methods, arbitrary headers, automatic retries with exponential backoff, and
never throws on failure — always resolves with an inspectable response object.
GET.3.30000.src/http-client.js:const { HttpClient } = require("./src/http-client");
const client = new HttpClient({
defaultHeaders: { Authorization: "Bearer <token>" },
maxRetries: 3,
});
request():// GET
const resp = await client.get("https://api.example.com/items");
// POST with JSON body
const resp = await client.post("https://api.example.com/items", {
body: { name: "widget" },
});
// PUT with custom headers
const resp = await client.put("https://api.example.com/items/1", {
headers: { "X-Request-Id": "abc123" },
body: { name: "updated" },
});
// DELETE
const resp = await client.delete("https://api.example.com/items/1");
// Generic form — any method
const resp = await client.request("PATCH", "https://api.example.com/items/1", {
body: { qty: 5 },
});
if (resp.ok) {
console.log(resp.body); // parsed JSON or raw string
console.log(resp.status); // e.g. 200
console.log(resp.headers); // response headers object
} else {
console.log(resp.error); // human-readable error (null if HTTP error with status)
console.log(resp.status); // HTTP status code or null for network errors
}
Every call resolves with an object containing:
| Key | Type | Description | |
|---|---|---|---|
| ----------- | ------------------- | ---------------------------------------------------- | |
ok | boolean | true if status is 2xx | |
status | `number \ | null` | HTTP status code; null for network-level errors |
headers | object | Response headers | |
body | any | Parsed JSON (if content-type is JSON), else string | |
error | `string \ | null` | Error description on failure; null on success |
resp.ok and resp.error.All options can be set at the client level (constructor) and overridden per-request:
| Option | Default | Description |
|---|---|---|
| ------------------ | ---------- | -------------------------------------- |
defaultHeaders | {} | Headers applied to every request |
maxRetries | 3 | Max retry attempts |
timeout | 30000 | Socket timeout in ms |
backoffBase | 500 | Base delay (ms) for exponential backoff |
backoffMax | 30000 | Maximum backoff delay cap (ms) |
None — uses only Node.js built-in modules (http, https, url).
共 1 个版本