【问题标题】:Unable to get data from REST Calls using Node.js无法使用 Node.js 从 REST 调用中获取数据
【发布时间】:2014-07-18 04:12:25
【问题描述】:

我正在从我的 php 和 Node.js 应用程序对返回 Json 对象的客户端提供的特定 URL 进行 REST API 调用。它适用于 PHP。但是,我无法从我的节点应用程序接收数据?有人可以帮助我的可能原因是什么?

注意:出于安全原因,我粘贴了一个虚拟 REST URI

  1. 它可以很好地与 PHP 一起工作,事实上我在几秒钟内就可以得到 json 格式的数据。

$响应 = file_get_contents('http://xyz.net/v2_resmgr/providers/pools');回声 $响应;

  1. 我使用 node.js 尝试相同的 url,但出现 TimeOut 错误。我也试过设置超时,但还是不行。

var job = new CronJob({ cronTime: '0 */3 * * * *', onTick: 函数 () {

  url=   "http://xyznet/v2_resmgr/providers/pools"; 


    var request = http.get(url, function (response) {

      var buffer = "",
        data,
        route;

      response.on("data", function (chunk) {
        buffer += chunk;
      });

      response.on("end", function (err) {
      console.log(buffer);

    });

request.setTimeout( 200000, function( ) {
    // handle timeout here
  console.log("Time Out call to the Rest API");
});

      });

  },
  start: true

});
job.start();

【问题讨论】:

    标签: javascript json node.js rest


    【解决方案1】:

    我不知道这是否是您正在寻找的答案,但是当您使用“请求”包时,生活会变得更轻松 (https://www.npmjs.org/package/request)

    下面是使用请求模块的代码:

    var request = require('request');
    request('http://xyznet/v2_resmgr/providers/pools', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Print the body of the response.
      }
    })
    


    更新:我编写了一些更接近您的帖子的代码。下面的代码不使用“请求”模块,它每 3 秒联系一次服务器。
    setInterval(function () {
        http.get('http://echo.jsontest.com/key/value', function (response) {
            var responseBody = '';
            response.on('data', function (chunk) {
                responseBody += chunk;
            });
            response.on('end', function () {
                console.log(responseBody);
                var object = JSON.parse(responseBody)
            });
        });
    }, 3000);
    

    【讨论】:

    • +1 用于提及请求。 99% 的时间它让您的生活更轻松。
    猜你喜欢
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多