在node.js Lambda函数和Alexa之间对API进行REST调用时遇到问题。我正在使用请求库来进行具有帐户关联技能的呼叫。我仅针对意图设置了一个示例话语,模拟器对此效果很好。
另外,cloudwatch日志显示了来自api端点的200响应代码以及从console.logs到CW的API返回的任何数据。
'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 () { 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); this.emit(':tell', speechOutput); } else { console.log(error + ' : ' + response.statusCode); this.emit(':tell', 'There was an error'); } }); }, 'AMAZON.HelpIntent': function () {} //.........And other built in intents. } };
我猜这与我要求Alexa“发出/讲”的SpeechOutput格式有关?
不,它与speechOutput的格式无关。问题是request执行该方法的回调时,对它的引用this会丢失。为了解决这个问题,请this在调用之前保留对它的引用request(例如,分配this给名为的变量self):
request
this
self
'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 () { self = this 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); self.emit(':tell', speechOutput); // USE SELF HERE } else { console.log(error + ' : ' + response.statusCode); self.emit(':tell', 'There was an error'); // AND HERE AS WELL } }); }, 'AMAZON.HelpIntent': function () {} //.........And other built in intents. } };