Shruti sharma
Shruti sharma

Reputation: 211

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

Upvotes: 0

Views: 2449

Answers (2)

Ronnie Smith
Ronnie Smith

Reputation: 18575

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

Upvotes: 1

O. Jones
O. Jones

Reputation: 108686

To request Basic authentication, a client passes a http Authorization header to the server. That header takes the form

    Authorization: Basic Base64EncodedCredentials

Therefore, your question is "how to pass a header with a https.get() request?"

It goes in options.headers{} and you can put it there like this:

const encodedCredentials = /* whatever your API requires */ 
const options = {
  headers: {
    'Authorization' : 'Basic ' + encodedCredentials
  }
}

const getUrl = https://rws322s213.infosys.com/AIAMFG/rest/v1/describe'
https.get (getUrl, options, (resp) => {
   /* handle the response here. */
})

Upvotes: 3

Related Questions