HTTPS
https.get()
Starts a native HTTPS GET request and ends the outgoing request automatically. Read the response and handle transport errors separately from HTTP status. This lab requires OpenSSL to generate a disposable self-signed certificate with a loopback IP SAN; trust only that specific certificate in the lab. Never disable verification in production. Tested on Node.js 22.16.0. Example output (one line per entry): ["200 book", "DEPTH_ZERO_SELF_SIGNED_CERT"].
Formal Syntax & Structure
nodejs syntaxnodejs
https.get(url[, options][, callback]); https.get(options[, callback])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| url | string | URL | Destination in the URL overload. |
| options | object | Request and TLS settings. |
| callback | Function | Response listener. |
Return Value
http.ClientRequest
The outgoing request.
Working Example
Example Snippetnodejs
import https from 'node:https';import { execFileSync } from 'node:child_process';import { mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';const dir = mkdtempSync(join(tmpdir(), 'bm-https-'));let server;try { execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', join(dir, 'key.pem'), '-out', join(dir, 'cert.pem'), '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=IP:127.0.0.1'], { stdio: 'ignore', timeout: 3000 }); const cert = readFileSync(join(dir, 'cert.pem')); server = https.createServer({ key: readFileSync(join(dir, 'key.pem')), cert }, (req, res) => res.end('book')); await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); const url = 'https://127.0.0.1:' + server.address().port; const get = ca => new Promise((resolve, reject) => { const request = https.get(url, { ca, rejectUnauthorized: true, agent: false }, response => { let body = ''; response.setEncoding('utf8'); response.on('data', chunk => body += chunk); response.on('end', () => resolve([response.statusCode, body])); response.on('error', reject); }); request.on('error', reject); request.setTimeout(1000, () => request.destroy(new Error('timeout'))); }); console.log(...await get(cert)); try { await get(undefined); } catch (e) { console.log(e.code); }}finally { if (server?.listening) { server.closeAllConnections(); await new Promise(r => server.close(r)); } rmSync(dir, { recursive: true, force: true });}