HTTPS client
GET with node:https
A global fetch is not in every runtime, so the built in https module is still the way to make a simple GET call by hand. Wrap the event based API in a promise to get clean await syntax. The sketch below collects text chunks into one string. The function needs a server with a certificate and a network, so it is not run on the page.
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. The function calls getText from the first block, and it needs a server with a certificate and a network, so it is not run on the page.
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. The function needs a server with a certificate and a network, so it is not run on the page.
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. The function needs a server with a certificate and a network, so it is not run on the page.
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(); }); }
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a call of
https.getgive back before the body has arrived?Answer
A request object that emits events and carries the response stream
The module is event based: the callback gets the response stream, and the body arrives in
datachunks untilend. -
Why wrap the event based call in a
Promise?Answer
So the caller can await one value and handle a failure with try and catch
The promise turns the
endanderrorevents into one settled value or one rejection. -
When does the
endevent of the response fire?Answer
After the last chunk of the body has arrived
The chunks arrive as
data, andendis the signal that the body is complete. -
A response arrives with
statusCode404. What doeshttps.getdo on its own?Answer
Nothing special: the response is delivered and the code must check the status
A 404 is a completed exchange, so the body still arrives and the handler decides to reject it.
-
What does this program print?
type User = { id: number; name: string }; const text = "{\"id\": 1, \"name\": \"Ada\"}"; const user = JSON.parse(text) as User; console.log(user.name);Answer
Ada
The parsed object has the field
namewith the value Ada, and the cast only tells the compiler its shape. -
What does this program print?
type User = { id: number; name: string }; const users: User[] = JSON.parse("[{\"id\":1,\"name\":\"Ada\"},{\"id\":2,\"name\":\"Bob\"}]") as User[]; console.log(users.length, users[1].name);Answer
2 Bob
The array holds two users, and the second one is Bob.
-
What does the compiler say about this program?
type User = { id: number; name: string }; const user: User = "{\"id\": 1}"; console.log(user.name);Answer
error TS2322: Type 'string' is not assignable to type 'User'.
The text of a JSON body is still a string until it is parsed, so the annotation asks for a parse first.
-
What does the compiler say about this program?
import * as https from "https"; const res: string = https.get("https://example.com"); console.log(res);Answer
error TS2322: Type 'ClientRequest' is not assignable to type 'string'.
https.getreturns the request object, and the body comes later through the response events. -
A program wraps
https.getin a promise but never listens for theerrorevent. What can happen?Answer
A network fault leaves the promise pending forever
Only
endsettles the promise, so a fault that emitserrorinstead never calls resolve or reject. -
A program parses every response body with
JSON.parsewithout checkingstatusCode. What is the problem?Answer
A failed status often carries an HTML or text body, so the parse throws an unrelated error
A 404 page is not JSON, so the parse fails on the text of the error page instead of reporting the status.
Article author: Arthur Isaev