【问题标题】:Get the result outside of the http call在 http 调用之外获取结果
【发布时间】:2019-06-07 14:39:48
【问题描述】:

在我们的项目中,我们使用 HTTP 请求通过 Node 调用 REST Web 服务。当我们将它登录到控制台时,我们可以看到结果。但我们想在 HTTP 请求之外存储或使用它。我们怎样才能做到这一点?

var http = require('http');

var options = {
  host: 'http:\\example.com',
  port: 80,
  path : '/site/status?tag=A7351&date=09JAN&name=LASTNAME',
  method : 'GET'
};

var result;

http.request(options, function(res){
  var body = '';

  res.on('data', function (chunk) {
    body += chunk;
  });
  res.on('end', function () {
    result = JSON.parse(body);
    console.log(result, "INSIDE"); //Shows the JSON result
  });
}).end();

console.log(result, "OUTSIDE"); //Shows Undefined

结果格式如下:

{
  error: 0,
  statut: 'STATUTTTTT',
  origine: 'PLACEEE',
  destination: 'PARIS',
  onwardDate: null
}

我们需要能够在 HTTP 调用之外获得结果。

【问题讨论】:

标签: node.js json heroku httprequest dialogflow-es


【解决方案1】:

问题是您正在进行异步调用,但没有正确处理它。 Dialogflow 的库要求您在进行异步调用时返回一个 Promise。

最简单的解决方案是让您从使用请求库切换到使用request-promise-native 库并返回 Promise。

有关示例和更多信息,请参阅 Stack Overflow 上的 other answers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多