HTTP request not working with AWS Lambda please help

+1 vote

I've been trying to run the following code, but unable to do so, please some one help.

var http = require('http');

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

  console.log('end request to ' + event.url);
}
Apr 13, 2018 in AWS by code_ninja
• 6,290 points

edited Apr 13, 2018 by code_ninja 15,845 views

10 answers to this question.

+1 vote
Best answer

context.done has to be included after the callbacks for request. Once context.done is called the function therefore causing your code to not function.

Here is the working code,

var http = require('http');

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

  console.log('end request to ' + event.url);
}

Update: starting 2017 the old Nodejs 0.10 has been deprecated by AWS and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)
answered Apr 13, 2018 by brat_1
• 7,200 points

selected Aug 3, 2018 by Priyaj
0 votes

I'm using the async utility module, which is easier to understand for newbies. You'll need to push that to your AWS Stack to use it (I recommend the serverless framework).

Note that the data comes back in chunks, which are gathered in a global variable, and finally the callback is called when the data has ended.

'use strict';

const async = require('async');
const https = require('https');

module.exports.handler = function (event, context, callback) {

    let body = "";
    let countChunks = 0;

    async.waterfall([
        requestDataFromFeed,
        // processBody,
    ], (err, result) => {
        if (err) {
            console.log(err);
            callback(err);
        }
        else {
            const message = "Success";
            console.log(result.body);
            callback(null, message);
        }
    });

    function requestDataFromFeed(callback) {
        const url = 'https://put-your-feed-here.com';
        console.log(`Sending GET request to ${url}`);
        https.get(url, (response) => {
            console.log('statusCode:', response.statusCode);
            response.on('data', (chunk) => {
                countChunks++;
                body += chunk;
            });
            response.on('end', () => {
                const result = {
                    countChunks: countChunks,
                    body: body
                };
                callback(null, result);
            });
        }).on('error', (err) => {
            console.log(err);
            callback(err);
        });
    }
};

answered Aug 3, 2018 by Priyaj
• 58,090 points
0 votes

Try this it works

var http = require('http');

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

  console.log('end request to ' + event.url);
}
answered Dec 10, 2018 by Shuvodip
0 votes

You can use this code

const http = require('http');
exports.handler = async (event, context) => {
    return new Promise((resolve, reject) => {
        const options = {
            host: 'ec2-18-191-89-162.us-east-2.compute.amazonaws.com',
            path: '/api/repos/r1639420d605/index?delta=true&clear=false',
            port: 8000,
            method: 'PUT'
        };
        const req = http.request(options, (res) => {
          resolve('Success');
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
        req.write('');
        req.end();
    });
};
answered Dec 10, 2018 by Sujeet
0 votes
Read this article to get a brief example of how to request http with aws lambda function

https://dev.to/scottlepp/http-request-with-aws-lambda-nodejs-810-and-standard-http-library-2cee
answered Dec 10, 2018 by User57092
0 votes

The newer version of NodeJS doesn't support the previous function statement

use this instead 

function(event, context, callback)
answered Dec 10, 2018 by Ghosh
0 votes

I think that this might be caused due to a missing user-agent in your HTTP request.

answered Dec 10, 2018 by bugseeker
0 votes
See how to configure your lambda fucntion https://docs.aws.amazon.com/lambda/latest/dg/vpc.html
answered Dec 10, 2018 by Prateek
0 votes

I found this code and it helped me

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

answered Dec 10, 2018 by Tulika
0 votes

have a look at the Serverless nodejs framework when you want to develop locally then deploy to AWS, will make your workflow much easier

answered Dec 10, 2018 by findingbugs

Related Questions In AWS

0 votes
1 answer
0 votes
1 answer

AWS Lamda with Proxy Integration not recieving request parameters

The lambda proxy integration should pass through ...READ MORE

answered Sep 19, 2018 in AWS by Priyaj
• 58,090 points
720 views
0 votes
1 answer

Could you please demonstrate aws lambda with python

Hey @Priyanka,  Python Lambda functions are functions that ...READ MORE

answered Jun 24, 2019 in AWS by Kalgi
• 52,360 points
660 views
+3 votes
3 answers
+1 vote
3 answers

Not able to pass params POST to AWS Lambda from Amazon API Gateway

For this template : application/x-www-form-urlencoded  This line below will ...READ MORE

answered Jun 13, 2018 in AWS by Cloud gunner
• 4,670 points
8,369 views
0 votes
1 answer
0 votes
1 answer
+2 votes
3 answers
+3 votes
4 answers

How to host a website on AWS?

Certainly, it can be used to do ...READ MORE

answered Mar 30, 2018 in AWS by brat_1
• 7,200 points
2,519 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP