Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


rest.getJSON(options,
        function(statusCode, result)
        {
            // I could work with the result html/json here.  I could also just return it
            console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
            res.statusCode = statusCode;
            res.send(result);
        });
var http = require("http");
var https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */
exports.getJSON = function(options, onResult)
{
    console.log("rest::getJSON");

    var prot = options.port == 443 ? https : http;
    var req = prot.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });

    req.end();
};
var options = {
    host: 'somesite.com',
    port: 443,
    path: '/some/path',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

@StErMi - I updated the end of the post with a sample.

@bryanmac can you please send/add the complete sample?

@bryanmac with your permission I would like to use this code grunt plugin i'm currently building. Not sure when but it would be made open sourced when completed.

For example, in a service, I require the rest module above and then do this.

Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

I have a more complete sample if you're interested.

It's a sample where node.js is using parse.com as a back so it sends REST requests over http. To get it to work, you need the parse.com app id/key in /service/secrets.js

Look in /express/helloworld

and providing a callback function.

yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

Here are a couple of code examples for Node.js:

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

You can jump straight to the Node docs here

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


rest.getJSON(options, function(statusCode, result) {
    // I could work with the result html/json here.  I could also just return it
    console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
    res.statusCode = statusCode;
    res.send(result);
});
var http = require("http");
var https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */
exports.getJSON = function(options, onResult)
{
    console.log("rest::getJSON");

    var port = options.port == 443 ? https : http;
    var req = port.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });

    req.end();
};
var options = {
    host: 'somesite.com',
    port: 443,
    path: '/some/path',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

@StErMi - I updated the end of the post with a sample.

@bryanmac can you please send/add the complete sample?

For example, in a service, I require the rest module above and then do this.

Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

If you're looking for async await (linear no callback), promises, compile time support and intellisense, we create a lightweight http and rest client that fits that bill:

and providing a callback function.

yes - request module is simple but this is lower level showing what libraries like request module is doing. If you need lower level control or http requests (showing progress on large downloads etc...), this shows how it's done.

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);

Just do the following for GET method request:

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


+1 for keeping the callback node way! function(err, res){ }

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


http.get(options, callback)
var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

@DanDascalescu: ya, if you want to process the body as a whole (which is likely) then you probably want to buffer it and process on 'end'. I'll update my answer too for completeness.

Thanks for the update. Looks like there's a need for an 'end' handler to concatenate the chunks then. Which basically amounts to @bryanmac's answer?

There is also a general http.request(options, callback) function which allows you to specify the request method and other request details.

Where's the content of the server's response that the OP asked for?

sorry, i can't figure out what parameters callback is called with...how can i get body and where is the reference for parameters and properties of that parameters.

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

Here are a couple of code examples for Node.js:

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

You can jump straight to the Node docs here

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


+1 for keeping the callback node way! function(err, res){ }

Check out httpreq: it's a node library I created because I was frustrated there was no simple http GET or POST module out there ;-)

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


client.js
let RequestClient = require("reqclient").RequestClient

let client = new RequestClient({
  baseUrl: "https://myapp.com/api/v1",
  cache: true,
  auth: {user: "admin", pass: "secret"}
})

module.exports = client
let client = require('client')
//let router = ...

router.get('/dashboard', (req, res) => {
  // Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
  client.get("reports/clients")
    .then(response => {
       console.log("Report for client", response.userId)  // REST responses are parsed as JSON objects
       res.render('clients/dashboard', {title: 'Customer Report', report: response})
    })
    .catch(err => {
      console.error("Ups!", err)
      res.status(400).render('error', {error: err})
    })
})

router.get('/orders', (req, res, next) => {
  // GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
  client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
    .then(orders => {
      res.render('clients/orders', {title: 'Customer Orders', orders: orders})
    })
    .catch(err => someErrorHandler(req, res, next))
})

router.delete('/orders', (req, res, next) => {
  // DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
  client.delete({
    "uri": "orders/{client}/{id}",
    "params": {"client": "A987", "id": 1234}
  })
  .then(resp => res.status(204))
  .catch(err => someErrorHandler(req, res, next))
})

And in the controllers where you need to consume the API use like this:

The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:

Use reqclient: not designed for scripting purpose like request or many other libraries. Reqclient allows in the constructor specify many configurations useful when you need to reuse the same configuration again and again: base URL, headers, auth options, logging options, caching, etc. Also has useful features like query and URL parsing, automatic query encoding and JSON parsing, etc.

reqclient supports many features, but it has some that are not supported by other libraries: OAuth2 integration and logger integration with cURL syntax, and always returns native Promise objects.

Note
Rectangle 27 1

javascript HTTP GET Request in Node.js Express?


request
var request=require('request');

request.get('https://someplace',options,function(err,res,body){
  if(err) //TODO: handle err
  if(res.statusCode !== 200 ) //etc
  //TODO Do something with response
});

Request and Superagent are pretty good libraries to use.

Should it be res.statusCode === 200 in second if ? )

Note