简体   繁体   English

无法使用Node.js从REST调用中获取数据

[英]Unable to get data from REST Calls using Node.js

I am making a REST API call from my php and Node.js application to a particular URL provided by the client which returns a Json object. 我正在从我的php和Node.js应用程序对客户端提供的特定URL进行REST API调用,该URL返回Json对象。 It works fine from with the PHP. 从PHP可以正常工作。 However, I am unable to receive data from my node application? 但是,我无法从节点应用程序接收数据吗? What might be the possible reason can someone help me ? 有人可以帮助我的可能原因是什么?

Note: I have pasted a dummy REST URI for security reasons 注意:出于安全原因,我粘贴了一个虚拟的REST URI

  1. It works fine with PHP infact i get the json formatted data in like couple of seconds. 它实际上可以与PHP正常工作,我可以在几秒钟内获得json格式的数据。

$response = file_get_contents(' http://xyz.net/v2_resmgr/providers/pools '); $ response = file_get_contents(' http://xyz.net/v2_resmgr/providers/pools '); echo $response; echo $ response;

  1. I try the same url using node.js i get a TimeOut error. 我使用node.js尝试相同的网址,但出现超时错误。 I also tried setting the timeout but it would still not work. 我也尝试设置超时,但仍然无法正常工作。

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

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

I don't know if this is the answer you are looking for, but life gets easier when you use the 'request' package ( https://www.npmjs.org/package/request ) 我不知道这是否是您要寻找的答案,但是当您使用“请求”包( https://www.npmjs.org/package/request )时,生活会变得更轻松

Here is what the code would look like using the request module: 使用请求模块的代码如下所示:

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.
  }
})


Update: I coded something a little closer to your post. 更新:我对您的帖子进行了一些编码。 The code below does not use the "request" module and it contacts the server every 3 seconds. 下面的代码不使用“请求”模块,而是每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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM