Alexa API技能 - nodejs获取请求未执行

时间:2018-05-08 19:58:51

标签: node.js request aws-lambda httprequest alexa-skills-kit

我正在处理我的第一个Alexa skill,并且作为起点,希望Alexa声明从简单的GET请求中检索的数据(请参阅下面的lambda函数)。但是,出于某种原因,请求实际上似乎并没有执行 - request.get()内部没有任何内容正在打印到控制台,而speechOutput是“外部请求”。处理程序执行后。我也很擅长浏览CloudWatch日志,并且无法找到有关网络请求的任何信息,甚至无法知道是否正在尝试这样做。欢迎任何帮助!

'use strict';
//Required node packages
const alexa = require('./node_modules/alexa-sdk');
const request = require('request');
// var https = require('https')

//this is the handler, when the lambda is invoked, this is whats called
exports.handler = function (event, context, callback) {
  const skill = alexa.handler(event, context);

  skill.appId = '<app_id>';
  skill.registerHandlers(handlers);
  skill.execute();
};

//Alexa handlers
const handlers = {
  'LaunchRequest': function () {
    console.log("inside of LaunchRequest");
    const speechOutput = "Hello from NASA!";
    this.response.speak(speechOutput).listen(speechOutput);
    this.emit(':responseReady');
  },

  //Entering our main, part finding function
  'GetAPOD': function () {
    const intent_context= this
    const speechOutput = getData()
    intent_context.response.speak(speechOutput).listen(speechOutput);
    intent_context.emit(':responseReady');

  },

  'Unhandled': function (){
    console.log("inside of unhandled");
    const speechOutput = "I didn't understand that.  Please try again";
    this.response.speak(speechOutput).listen(speechOutput);
    this.emit(':responseReady');

  }
};

const getData = function() {
  const url = "https://api.nasa.gov/planetary/apod?api_key=<key>"
  console.log("inside get data")
  request.get(url, function (error, response, body) {
    console.log("inside request")
    console.log('error', error) //Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    console.log('body:', body); // Print the HTML for the Google homepage.
    return "complete request"
    return body
  });

  return "outside request"
}

1 个答案:

答案 0 :(得分:1)

我在过去发现,这样的API请求会被破坏,因为它们不是同步的,就像大卫所说的那样。为了解决这个问题,我不得不把这个请求放在一个让它解决的承诺中,在你的情况下类似于这个:

更改您的功能以包含承诺:

function getData = function() {
 const url = "https://api.nasa.gov/planetary/apod?api_key=<key>"
 console.log("inside get data")
    return new Promise(function(resolve, reject) {
        request.get(url, function (error, response, body) {
            if (err) {
                reject(err);
            }

            if (body) {
                resolve(JSON.parse(body));
            }
        });
    });
}

然后更改你的意图处理程序以使用promise:

   //Entering our main, part finding function
  'GetAPOD': function () {
    getData()
   .then(function(body) {
    let speechOutput = body;
    intent_context.response.speak(speechOutput).listen(speechOutput);
    intent_context.emit(':responseReady');
    }

这些方面的东西。您需要稍微玩一下以确保结果按照您的意愿生成。希望这可以帮助。 d