blackmamba blackmamba - 4 years ago 240
reST (reStructuredText) Question

Access rest api using nodejs

I am trying to access and using their REST API.
I got this code from How to make remote REST call inside Node.js? any CURL?. But it is not fetching any data. I tried wget on the url and it worked perfectly fine.


var https = require('http');

var optionsget = {
host : '',

port : 8080,
path : '/v0.2/companies/search?q=barclays+bank&jurisdiction_code=gb',
method : 'GET'
};'Options prepared:');;'Do the GET call');

var reqGET = https.get(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);

res.on('data', function(d) {'GET result:\n');
process.stdout.write(d);'\n\nCall completed');


reqGet.on('error', function(e) {

Answer Source

Because Node runs asynchronously, the returned data is broken into chunks.

The .on('data') event returns a portion of the data, which you then need to stitch/append back to a variable. You can then capture the complete output with .on('end').

See this example for more info: Why is node.js breaking incoming data into chunks? (@vossad01's answer)

That said, @SilviuBurcea's suggestion to use request is a much simpler way of handling http requests so you don't have to write and handle all of this yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download