node.js AWS Lambda 中的 HTTP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31812846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:12:46  来源:igfitidea点击:

HTTP Requests in an AWS Lambda

node.jsamazon-web-servicesaws-lambda

提问by kevin628

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 httpor httpsmodules, I get an ECONNREFUSED.

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

Here's my Lambda:

这是我的 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?

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

Any guidance is appreciated.

任何指导表示赞赏。

采纳答案by kevin628

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.

显然,如果您决定将 URL 作为第一个参数提供给.get(),则必须包含http://URL 的前面,例如,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 hostnamecan be the simple form of the URL. Example:

或者,您可以将第一个参数指定为 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");
  });
};