【问题标题】:HTTP Requests in an AWS LambdaAWS Lambda 中的 HTTP 请求
【发布时间】:2015-10-27 01:38:42
【问题描述】:

我是 Lambdas 新手,所以也许我还没有掌握一些东西,但我编写了一个简单的 Lambda 函数来向外部站点发出 HTTP 请求。出于某种原因,无论我使用 Node 的 http 还是 https 模块,我都会得到一个 ECONNREFUSED

这是我的 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");
    });
};

这是日志输出:

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

我是否需要角色权限才能执行 HTTP 请求? Lambda 甚至允许普通的旧 HTTP 请求吗?我需要设置特殊的标题吗?

感谢任何指导。

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda


    【解决方案1】:

    我解决了自己的问题。

    显然,如果您决定将 URL 作为第一个参数提供给 .get(),则必须在 URL 前面包含 http://,例如 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");
      });
    };
    

    或者,您可以将第一个参数指定为hash of options,其中hostname 可以是URL 的简单形式。示例:

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

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 2019-06-14
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 2019-01-09
      • 2021-02-11
      相关资源
      最近更新 更多