0

我正在開展一個學校項目,並試圖從URL中獲取數據以便與我的Alexa技能集成。我絕對是一個NodeJS初學者,並沒有很多HTML或JSON的背景知識。針對亞馬遜Alexa技巧的NodeJS問題

我的學校有一個「API」我們的運輸系統在這裏:https://prtstatus.wvu.edu/api/ 樣本情況下帶有時間戳是在這裏:https://prtstatus.wvu.edu/api/1501906657/?format=json

在我的代碼,我試圖讓解析爲JSON字符串從從URL中獲取,但遇到了格式化問題,以便字符串的「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); 
}, 

回答

0

有幾個需要在代碼中解決的事情:

  1. 在選項中,你不需要指定協議。根據http文檔,選項主機應該只是域名。所以在這種情況下,它將是「prtstatus.wvu.edu」

  2. object.message在回調完成之前正在使用。因此,你可能會看到像「不能讀取屬性」消息「未定義」的錯誤。需要發生的是3行(this.attributes ...)是回調本身的一部分。