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.

  1. What does a call of https.get give 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 data chunks until end.

  2. 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 end and error events into one settled value or one rejection.

  3. When does the end event of the response fire?

    Answer

    After the last chunk of the body has arrived

    The chunks arrive as data, and end is the signal that the body is complete.

  4. A response arrives with statusCode 404. What does https.get do 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.

  5. 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 name with the value Ada, and the cast only tells the compiler its shape.

  6. 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.

  7. 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.

  8. 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.get returns the request object, and the body comes later through the response events.

  9. A program wraps https.get in a promise but never listens for the error event. What can happen?

    Answer

    A network fault leaves the promise pending forever

    Only end settles the promise, so a fault that emits error instead never calls resolve or reject.

  10. A program parses every response body with JSON.parse without checking statusCode. 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