简体   繁体   中英

HTTP Requests in an AWS Lambda

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.

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, eg, 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");
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM