Amazon Alexa 技能的 NodeJS 问题

NodeJS Issue for Amazon Alexa Skill

我正在做一个学校项目,我正在尝试从 URL 获取数据以与我的 Alexa Skill 集成。我绝对是一个 NodeJS 初学者,并且没有太多 HTML 或 JSON 的背景。

我的学校在这里有一个 "API" 交通系统:https://prtstatus.wvu.edu/api/ 带有时间戳的示例案例如下:https://prtstatus.wvu.edu/api/1501906657/?format=json

在我的代码中,我试图将来自 URL 的字符串解析为 JSON,但是 运行 遇到格式化问题,以便 "message:" 部分字符串将被传递。这是我在 AWS Lambda 中的意图代码:

'getPRTStatus': function() {
    var date = Math.round(new Date().getTime()/1000);
    var http = require('http');
    var https = require('https');

    var options = {
        host: 'https://prtstatus.wvu.edu',
        path: '/api/'+date+'/?format=json'
    };
    var object;
    var callback = function(response) {
        var str = '';

        //another chunk of data has been recieved, so append it to `str`
        response.on('data', function (chunk) {
            str += chunk;
        });

        //the whole response has been recieved, so we just print it out here
        response.on('end', function () {
            console.log(str);
            object = JSON.parse(str);
        });
    }

    https.request(options, callback).end();
    this.attributes.speechOutput = this.t(object.message);
    this.attributes.repromptSpeech = this.t(object.message);
    this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
},

有几件事需要在代码中解决:

  1. 在选项中,您不需要指定协议。根据 http 文档,选项 host 应该只是域名。所以在这种情况下它将是 "prtstatus.wvu.edu"

  2. 在回调完成之前正在使用 object.message。因此,您可能会看到类似 "Cannot read property 'message' of undefined" 的错误。需要发生的是 3 行 (this.attributes...) 成为回调本身的一部分。