在nodej中使用get API,并使用https进行身份验证

wwtsj6pe  于 2022-11-29  发布在  Node.js
关注(0)|答案(2)|浏览(118)

我如何发送Id and password意味着basic authentication到下面的代码。我的意思是我需要在下面的代码中放置id/pass?我的API需要基本的身份验证

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

6mzjoqzu1#

为了请求Basic authentication,客户端向服务器传递一个http Authorization header

Authorization: Basic Base64EncodedCredentials

因此,您的问题是“如何通过https.get()请求传递头文件?”
options.headers{},您可以这样放置它:

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. */
})
rekjcdws

rekjcdws2#

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

相关问题