Make an HTTPS request in Node.js
node-js
Published · Updated
For a low-level HTTPS request, Node exposes node:https. Save this as an ES module (for example, request.mjs). The response arrives as a stream, so collect its chunks before parsing:
import https from 'node:https';
https.get('https://example.com/data', (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => {
if (res.statusCode < 200 || res.statusCode >= 300) {
console.error(`HTTP ${res.statusCode}`);
return;
}
console.log(body);
});
}).on('error', console.error);
For new code, the promise-based fetch() API is usually easier to read; see Make a GET request in Node.js. Whichever client you choose, check status codes, set timeouts, limit response sizes, and handle connection errors. Never disable TLS certificate verification to make a failing request “work”; diagnose the hostname, certificate chain, proxy, or local trust store instead.
Sources
related.
Ruslan
About the author