Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in AWS by (880 points)

Can you help me out with this program?
I am unable to run this code.

varx http = require('http');
exports.handler = function(eventa, contextb) {
console.log('start request to ' + eventa.url)
http.get(eventa.url, function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'ERROR');
});
console.log('end request to ' + eventa.url);
}

1 Answer

0 votes
by (12.4k points)

Here is the working code, you can try this:

const http = require('https')

exports.handler = async (event) => {

    return httprequest().then((data) => {

        const response = {

            statusCode: 200,

            body: JSON.stringify(data),

        };

    return response;

    });

};

function httprequest() {

     return new Promise((resolve, reject) => {

        const options = {

            host: 'jsonplaceholder.typicode.com',

            path: '/todos',

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

        });

        // send the request

       req.end();

    });

}

Hope this works.

Are Interested in learning AWS? Come & join: AWS Online training

Want to know more about AWS Lambda, check out:

Related questions

+7 votes
1 answer

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

Browse Categories

...