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);
});
O. Jones
110k17 gold badges135 silver badges188 bronze badges
asked Jun 7, 2020 at 11:33

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. */
})
answered Jun 7, 2020 at 12:25
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');
}
answered Nov 27, 2022 at 23:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.