AWS Lambda 中 HTTP 请求的基本身份验证 node.js

Basic Authentication for HTTP request in AWS Lambda node.js

我使用 node.js 在我的 AWS Lambda 函数中有一个 http 请求。该代码工作正常,但是,我想访问需要 username/password 身份验证的 URL。如何在我的代码中实现它?

function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'api.plos.org',
            path: '/search?q=title:DNA',
            port: 443, 
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });

       req.end();
    });
}

您需要包含授权 header: 你可以通过base64编码制作一个"username:password"

function httprequest() {
    return new Promise((resolve, reject) => {
        const username = "john";
        const password = "1234";
        const auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

        const options = {
            host: 'api.plos.org',
            path: '/search?q=title:DNA',
            port: 443,
            headers: { Authorization: auth},
            method: 'GET'
        };
        const req = http.request(options, (res) => {
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
            reject(e.message);
        });

        req.end();
    });
}