0

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. It works fine from with the 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

  1. It works fine with PHP infact i get the json formatted data in like couple of seconds.

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

  1. I try the same url using node.js i get a TimeOut error. I also tried setting the timeout but it would still not work.

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

1 Answer 1

2

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)

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.

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for mentioning request. 99% of the time it makes your life easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.