【问题标题】:Node.JS Get data from Http Request POSTNode.JS 从 Http 请求 POST 中获取数据
【发布时间】:2018-03-29 14:54:41
【问题描述】:

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

  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() 之后如何获取 text 变量的内容?

非常感谢。

【问题讨论】:

    标签: node.js aws-lambda httprequest


    【解决方案1】:

    在请求之前声明文本。我希望它应该可以工作。

    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();
    

    【讨论】:

    • 这不起作用。我初始化为 var text = ' ';当文本最后打印时,它被打印为空白......
    • 尝试在 response.on('end') 块中写入最后三行
    猜你喜欢
    • 2019-11-26
    • 2013-11-01
    • 2016-05-03
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多