26

I'm new to Lambdas so perhaps there is something I've not caught on to just yet, but I've written a simple Lambda function to do an HTTP request to an external site. For some reason, whether I use Node's http or https modules, I get an ECONNREFUSED.

Here's my Lambda:

var http = require('http');

exports.handler = function (event, context) {
    http.get('www.google.com', function (result) {
        console.log('Success, with: ' + result.statusCode);
        context.done(null);
    }).on('error', function (err) {
        console.log('Error, with: ' + err.message);
        context.done("Failed");
    });
};

Here's the log output:

START RequestId: request hash
2015-08-04T14:57:56.744Z    request hash                Error, with: connect ECONNREFUSED
2015-08-04T14:57:56.744Z    request hash                {"errorMessage":"Failed"}
END RequestId: request hash

Is there a role permission I need to have to do HTTP requests? Does Lambda even permit plain old HTTP requests? Are there special headers I need to set?

Any guidance is appreciated.

1 Answer 1

20

I solved my own problem.

Apparently, if you decide to feed the URL in as the first parameter to .get(), you must include the http:// up front of the URL, e.g., http://www.google.com.

var http = require('http');

exports.handler = function (event, context) {
  http.get('http://www.google.com', function (result) {
    console.log('Success, with: ' + result.statusCode);
    context.done(null);
  }).on('error', function (err) {
    console.log('Error, with: ' + err.message);
    context.done("Failed");
  });
};

Alternatively, you can specify the first parameter as a hash of options, where hostname can be the simple form of the URL. Example:

var http = require('http');

exports.handler = function (event, context) {
  var getConfig = {
    hostname: 'www.google.com'
  };
  http.get(getConfig, function (result) {
    console.log('Success, with: ' + result.statusCode);
    context.done(null);
  }).on('error', function (err) {
    console.log('Error, with: ' + err.message);
    context.done("Failed");
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.