HTTPS client
| GET with node:https | |
| Parse JSON bodies | |
| Status and errors | |
| POST sketch |
GET with node:https
Node 16 ships no global fetch, so use the built in https module for simple GET calls. Wrap the event based API in a promise to get clean await syntax. The sketch below collects text chunks into one string.
import * as https from "https";
function getText(url: string): Promise<string> {
return new Promise((resolve, reject) => {
https.get(url, (res: any) => {
let body = "";
res.on("data", (chunk: any) => { body += chunk; });
res.on("end", () => resolve(body));
}).on("error", (err: any) => reject(err));
});
}
Parse JSON bodies
Most APIs return JSON text that must be parsed before use. Await the text, then call JSON dot parse to build the value. Cast the result to a declared interface so the rest of the code stays typed.
type User = { id: number; name: string };
async function getUser(url: string): Promise<User> {
const text = await getText(url);
return JSON.parse(text) as User;
}
Status and errors
A smooth network load can still carry a failed status such as not found. Check statusCode on the response and reject for codes outside the two hundred range. Network faults arrive on the error event and must reject too.
function getStrict(url: string): Promise<string> {
return new Promise((resolve, reject) => {
https.get(url, (res: any) => {
if ((res.statusCode ?? 0) >= 400) {
reject(new Error("bad status"));
return;
}
resolve("ok");
}).on("error", (err: any) => reject(err));
});
}
POST sketch
POST sends a body with options for method and headers. Stringify the payload, set content length, and write the text into the request. End the request so the server knows the body is complete.
function postJson(url: string, data: unknown): Promise<void> {
const text = JSON.stringify(data);
return new Promise((resolve, reject) => {
const req = https.request(url, { method: "POST" }, () => resolve());
req.on("error", (err: any) => reject(err));
req.write(text);
req.end();
});
}
Next: Abort and timeouts
Article author: Arthur Isaev