我开始使用AWS Lambda,并试图从我的处理函数请求外部服务.根据this answer的说法,HTTP请求应该可以正常工作,而我还没有找到任何其他说明.(事实上,人们已经发布了code that use the Twilio API to send SMS条.)

我的处理程序代码是:

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);
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
  });

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

我在CloudWatch日志(log)中看到以下4行:

2015-02-11 07:38:06 UTC START RequestId: eb19c89d-b1c0-11e4-bceb-d310b88d37e2
2015-02-11 07:38:06 UTC eb19c89d-b1c0-11e4-bceb-d310b88d37e2 start request to http://www.google.com
2015-02-11 07:38:06 UTC eb19c89d-b1c0-11e4-bceb-d310b88d37e2 end request to http://www.google.com
2015-02-11 07:38:06 UTC END RequestId: eb19c89d-b1c0-11e4-bceb-d310b88d37e2

我希望这里还有一行:

2015-02-11 07:38:06 UTC eb19c89d-b1c0-11e4-bceb-d310b88d37e2 Got response: 302

但这是缺失的.如果我在本地机器上使用的基本部分没有 node 中的处理程序包装器,那么代码将按预期工作.

我使用的inputfile.txt是用于invoke-async呼叫的:

{
   "url":"http://www.google.com"
}

处理程序代码中执行请求的部分似乎被完全跳过.我从request lib开始,后来又使用了plain http来创建一个最小的示例.我还试图请求一个我控制的服务的URL来判断日志(log),但没有收到任何请求.

我完全被难住了.Is there any reason Node and/or AWS Lambda would not execute the HTTP request?

推荐答案

当然,我误解了这个问题.As AWS themselves put it:

对于那些在Lambda第一次遇到nodejs的人,一个常见的

在对请求进行任何回调之前,我正在拨打context.done路,导致我的功能提前终止.

工作代码如下:

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:从2017年开始,AWS已经弃用了旧的Nodejs 0.10,现在只有更新的4.3运行时可用(旧功能应该更新).此运行时对处理程序函数进行了一些更改.新的处理程序现在有3个参数.

function(event, context, callback)

尽管您仍然可以在上下文参数中找到succeeddonefail,但AWS建议使用callback函数,否则默认情况下会返回null.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

完整的文件可以在http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html页找到

Node.js相关问答推荐

如何使用Node.js、Express和Mongoose创建多个API

使用Node.js中的";类型";:";模块";不导入文件

MongoDB的方面查询的Postgres类似功能

一个大型的单个 Redis 实例可以处理所有事情,还是多个 Redis 实例?

如何使用Next.js/Node/TS正确地上传至S3

为什么运行 yarn 命令会出错 - yargs-parser的完整性判断失败

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

使用 create-expo-app 时如何更改 webpack-config.js 中的哈希函数?

更新文档数组中的文档 Mongoose

从数据库读取数据并将其作为可下载的 zip 文件发送

为什么我的react 表单不能正常工作?

如何为一个网站实现这 2 个网址.即 www.administrator.sitename.com 和 www.sitename.com?

来自 Node-aws 的 Dynamo Local:所有操作都失败无法对不存在的表执行操作

ChildProcess 关闭、退出事件之间的区别

MongoDB Node findone如何处理没有结果?

Forever + Nodemon 一起运行

如何仅在丢失的路由上将 Express.js 设置为 404?

我应该如何在 webpack 中使用时刻时区?

找不到在 docker compose 环境中运行的 node js 应用程序的模块

如何从 Node.js 应用程序Ping?