0

I have a http request in my AWS Lambda function using node.js. The code works fine, however, I want to access a URL that needs a username/password authentication. How can I implement it in my code?

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();
    });
}
incnnu
  • 173
  • 3
  • 14

1 Answers1

2

You need to include the an Authorization header: You can make one by base64 encoding "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();
    });
}
Alboman
  • 325
  • 1
  • 6
  • 1
    [They say](https://stackoverflow.com/a/23097961/3473303) that on Node > 4 you can use `Buffer.from` rather than `new Buffer` – massic80 Sep 21 '21 at 15:28