Node.js Lambda function returns “The response is invalid” back to Alexa Service Simulator from REST call

后端 未结 2 1303
梦如初夏
梦如初夏 2020-12-21 15:52

Having issues making a REST call to an API between a node.js Lambda function and Alexa. I\'m using the request library to make the calls with an account linked skill. I\'ve

2条回答
  •  不思量自难忘°
    2020-12-21 16:17

    You are facing issue only because of asynchronous call behavior of NodeJS and nothing to do with request call. You can solve this either by using promises or by using callback from method. Below is snippet.

    'use strict';
    var http = require('http');
    var request = require('request');
    var Alexa = require('alexa-sdk');
    var APP_ID = "amzn1.ask.skill.XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXX";
    
    exports.handler = function(event, context, callback) {
        var alexa = Alexa.handler(event, context);
        alexa.appId = APP_ID;
        alexa.registerHandlers(handlers);
        alexa.execute();
    };
    
    var handlers = {
       'LaunchRequest': function () {
            this.emit(':tell', 'Hi!');
       },
    
       'ApiWelcomeIntent': function () {
            requestAPI( (message) => {
                this.emit(':tell', message);
            });
        },
        'AMAZON.HelpIntent': function () {} //.........And other built in intents.
    
        }
    };
    
    function requestAPI(callback) {
        request('https://some.web/api', function (error, response, body) {
            if (!error && response.statusCode == 200) {
            // from within the callback, write data to response, essentially returning it.
                var speechOutput = JSON.stringify(body);
                console.log(body + " :Raw output?");
                console.log(speechOutput + ' :JSON stringified');
                console.log(response.statusCode);
                callback(speechOutput);
            } else {
                console.log(error + ' : ' + response.statusCode);
                callback('There was an error');
            }
        });
    }
    

提交回复
热议问题