Alexa nodejs从亚马逊Lamdba访问url

基于这个例子,我创build了一个简单的Alexa技能: https : //github.com/alexa/skill-sample-nodejs-fact/blob/en-US/lambda/custom/index.js

现在,当GetNewFactIntent被调用时,我想让脚本在不同的服务器上logging一些东西。

这是我想要做的,但有一个问题, 不是它应该在http.getcallback。

'GetNewFactIntent': function () { //var thisisit = this; http.get("http://example.com", function(res) { //console.log("Got response: " + res.statusCode); const factArr = data; const factIndex = Math.floor(Math.random() * factArr.length); const randomFact = factArr[factIndex]; const speechOutput = GET_FACT_MESSAGE + randomFact; this.response.cardRenderer(SKILL_NAME, randomFact); this.response.speak(speechOutput); this.emit(':responseReady'); }).on('error', function(e) { //console.log("Got error: " + e.message); }); }, 

在上面的例子中, 需要replace这个工作吗?

this不会是你的想法,因为你在callback函数的上下文中。 有两种可能的解决scheme:

  1. 改用箭头function。 一个箭头函数保留了它所用范围的thisvariables: function () { ... } – > () => { }
  2. 声明var self = this; 在callback之外,然后用你的selfvariablesreplace你的callback。

例:

 function getStuff () { var self = this; http.get (..., function () { // Instead of this, use self here }) } 

有关更多信息,请参阅: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this