0

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

2 Answers 2

3

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. */
})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.