我目前正在为Amazon Alexa开发node.js代码。 我尝试写一个REST服务器,想要通过alexa的演讲输出更改,我也使用alexa-sdk。我收到这个错误:
TypeError: Cannot read property 'request' of undefined
at writeIntent (/var/task/index.js:41:14)
at /var/task/index.js:125:25
at IncomingMessage.<anonymous> (/var/task/getRestData.js:6:13)
at emitOne (events.js:77:13)
at IncomingMessage.emit (events.js:169:7)
at IncomingMessage.Readable.read (_stream_readable.js:360:10)
at flow (_stream_readable.js:743:26)
at resume_ (_stream_readable.js:723:3)
at nextTickCallbackWith2Args (node.js:437:9)
at process._tickDomainCallback (node.js:392:17)
这是writeIntent函数:
//main helper function for write-intents
function writeIntent(slot, report, slotURL, event, context) {
var http = require('http');
var options = {
host: '1.2.345.678',
path: '/path/' + slotURL,
port: '8020',
method: 'POST',
'Content-Type': 'application/json'
};
callback = function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
if (report.toString() !== '') {
output(report, context);
}
});
};
//write alexa slot to server
if (event.request.type === "IntentRequest") {
var req = http.request(options, callback);
var postData = '{"$type":"string","?value":"' + slot + '"}';
req.write(postData);
req.end();
}
}
这是index.js中的intent处理程序中的代码:
var rest = require('./getRestData');
slot = 'Weather';
rest.getRestData('varWeatherState', function (state) {
rest.getRestData('varWeatherTemperature', function (temp) {
report += slot + ', the weather is ' + state
+ ', the temperature is ' + temp;
writeIntent(slot, report, 'varTheme', this.event, this.context);
writeIntent((new Date).getTime(), '',
'varThemeTrigger', this.event, this.context);
});
});
这是getRestData函数:
var getRestData = function (node, callback) {
var http = require('http');
var url = 'http://website.com/' + node + '?value';
http.get(url, function (response) {
response.on('data', function (data) {
callback(data);
});
});
}
exports.getRestData = getRestData;
事件被定义为index.js中的参数:
exports.handler = function (event, context) {
//init alexa-sdk
var Alexa = require('alexa-sdk');
var alexa = Alexa.handler(event, context);
alexa.appId = 'amzn1.ask.skill.2732c691-3bcc-4741-80f9-ddf57405be70';
alexa.registerHandlers(handlers);
alexa.execute();
};
在getRestData函数之外,我可以使用this.event访问事件。 如何将事件(和上下文)通过getRestData提供给writeIntent?