Умение Alexa API - nodejs получает запрос не выполняется - PullRequest
0 голосов
/ 08 мая 2018

Я работаю над своим первым навыком Alexa и, в качестве отправной точки, хотел бы, чтобы Alexa указывал данные, полученные из простого запроса GET (см. Функцию лямбда-выражения ниже).По какой-то причине, однако, запрос на самом деле, кажется, не выполняется - ничего из внутри request.get () не выводится на консоль, а speechOutput имеет значение «Outside Request» после выполнения обработчика.Я также новичок в просмотре журналов 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 голосов
/ 09 мая 2018

В прошлом я обнаружил, что такие запросы 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));
            }
        });
    });
}

Затем измените ваш обработчик намерений, чтобы использовать обещание:

   //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

...