Node.js HTTPS GET w Basic Authentication Working Example

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');
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ronnie Royston

Tulane Graduate (Philosophy '97), Cisco Certified Internetworking Expert# 6824, USPA Master Skydiver (D# 20776).