Node.JS从Http Request POST获取数据

时间:2018-03-29 14:54:42

标签: node.js aws-lambda httprequest

我是Node.js的新手,我正在Node.js中编写AWS Lambda函数,以从REST端点获取数据并将数据发送回Alexa。以下是我的代码片段:

  var req = http.request(post_options, function(response) {
      var str = '';

      response.setEncoding('utf8');

      //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() {

          var result = JSON.parse(str);

          text = 'According to Weather Underground, the temperature in ' + citySlot + ',' + stateSlot + ' feels like ';
          text += result.HighFahr0 + " degrees fahrenheit.";

          console.log("text::"+text);
      });
  });

  req.write(post_data);
  //this.emit(':ask', text, "Anything else i can help you with?");
  req.end();

如果我在构建文本字符串后立即执行this.emit,则它不起作用。如果我在req.write函数之后执行this.emit,则text变量超出范围并且不包含任何内容。如何在req.write()和req.end()之后获取文本变量的内容?

非常感谢。

1 个答案:

答案 0 :(得分:0)

在请求之前声明文本。我希望它应该有用。

var text;
var req = http.request(post_options, function(response) {
      var str = '';

      response.setEncoding('utf8');

      //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() {

          var result = JSON.parse(str);

          text = 'According to Weather Underground, the temperature in ' + citySlot + ',' + stateSlot + ' feels like ';
          text += result.HighFahr0 + " degrees fahrenheit.";

          console.log("text::"+text);
      });
  });

  req.write(post_data);
  this.emit(':ask', text, "Anything else i can help you with?");
  req.end();