Search code examples
node.jsresthttp-headershttp-authentication

Consuming get API in nodejs with authentication using https


How can I send Id and password means basic authentication to below code. I mean where I need to put id/pass in below code? My API needs basic authentication

const https = require('https');

https.get('https://rws322s213.infosys.com/AIAMFG/rest/v1/describe', (resp) => {
  let data = '';
  resp.on('data', (chunk) => {
    data += chunk;
  });


  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

Solution

  • const https = require('https');
    const httpsAgent = new https.Agent({
          rejectUnauthorized: false,
    });
    // Allow SELF_SIGNED_CERT, aka set rejectUnauthorized: false
    let options = {
        agent: httpsAgent
    }
    let address = "10.10.10.1";
    let path = "/api/v1/foo";
    let url = new URL(`https://${address}${path}`);
    url.username = "joe";
    url.password = "password123";
    
    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);
        });
    });
    
    try {
        let result = await apiCall;
    } catch (e) {
        console.error(e);
    } finally {
        console.log('We do cleanup here');
    }