Node.js HTTPS GET w Basic Authentication Working Example

Ronnie Royston
1 min readDec 17, 2022

Node.js is a cross platform open source JavaScript server environment that runs on the V8 or ChakraCore JavaScript engine. Node.js executes JavaScript code outside a web browser.

Below is a working example of using Node’s HTTPS module to make an API call on a remote server using ECMAScript Async/Await syntax.

const https = require('https');

// Optionally allow SELF_SIGNED_CERT, aka set rejectUnauthorized: false
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
let options = {
agent: httpsAgent
}

//API specifics - address, path, username, password
let address = "10.10.10.1";
let path = "/api/v1/foo";
let url = new URL(`https://${address}${path}`);
url.username = "joe";
url.password = "password123";

//wrap in a promise
let apiCall = new Promise(function (resolve, reject) {
var data = '';
https.get(url, options, res => {
res.on('data', function (chunk){ data += chunk })
res.on('end', function () {
resolve(data);
})
}).on('error', function (e) {
reject(e);
});
});

async function myApiCall(){
try {
let result = await apiCall;
} catch (e) {
console.error(e);
} finally {
console.log('We do cleanup here');
}
}

--

--

Ronnie Royston

Delivering refined solutions via vigorous practice. Tulane ('97), Cisco CCIE# 6824, Google Certified Professional Cloud Architect, and USPA Master Skydiver