如何使用nodejs AWS Lambda发送http请求?

我正在使用AWS Lambda来推动Alexa技能套件开发。 为了跟踪事件,我希望脚本在启动时发送一个HTTP请求,但是从云日志看来,好像在执行过程中跳过了http.get函数。

代码如下所示(google.com取代了已经在浏览器中testing过的分析跟踪url)。

exports.handler = function (event, context) { var skill = new WiseGuySkill(); var http = require('http'); var url = 'http://www.google.com'; console.log('start request to ' + url) http.get(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 ' + url); skill.execute(event, context); }; 

上下文对象已被注释掉,以允许“skill.execute”正常工作,但这种HTTP请求没有执行。 只logging“开始”和“结束”console.logs,那些内部的function不会。

这是一个asynchronous的问题? 谢谢。

你需要确保处理程序正在被触发。 有两种方法可以完成这个任务:

  • 您可以设置一个新的API端点并执行一个请求。
  • 你可以点击testingbutton,你的函数将被调用给定的数据。

我复制并粘贴除了第一行和最后一行以外的所有代码(因为我没有在任何地方定义customSkill )。 我能够得到一个200响应代码。

为了成功完成http请求,必须将http.get函数合并到callback函数中。 否则,进程将不会完成,并且会提前结束,使用callback允许http请求完成(有或没有错误),然后继续执行其余的function。

 WiseGuySkill.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) { // Call requestFunction to make the http.get call. // Get response from requestFunction using requestCallback requestFunction(function requestCallback(err) { // If error occurs during http.get request - respond with console.log if (err) { console.log('HTTP Error: request not sent'); } ContinueIntent(session,response); }); }; 

函数'requestFunction'调用http.get并触发callback。

 function requestFunction(requestCallback){ var url = "http://www.google.com"; http.get(url, function(res) { console.log("Got response: " + res.statusCode); requestCallback(null); }).on('error', function (e) { console.log("Got error: ", e); }); } 

很明显,确保你在脚本开始时需要'http'。 希望这可以帮助任何新来的人!