Follow me if you want to grow your full-stack JavaScript skills with my screencasts and courses.

REST in peace

Simple GET call to service

app.js
  

  var http = require('http');

  var options = {
    host: 'api-sandbox.oanda.com',
    port: 80,
    path: '/v1/quote?instruments=USD_ZAR',
    method: 'GET'
  };

  http.request(options, function(res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function (chunk) {
      body += chunk;
    });

    res.on('end', function(){
      var price = JSON.parse(body);
      console.log(price);
    });

  }).end();

  

After refactoring

app.js
  

  var http = require('http');

  function getJSON(options, cb){
      http.request(options, function(res){
          var body = '';

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

          res.on('end', function(){
              var result = JSON.parse(body);
              cb(null, result);
          });

          res.on('error', cb);
      })
      .on('error', cb)
      .end();
  }

  var options = {
      host: 'tagtreeeeee.tv',
      port: 80,
      path: '/v1/quote?instruments=USD_ZAR',
      method: 'GET'
  };

  getJSON(options, function(err, result){
      if(err){
          return console.log('Error while trying to get price: ', err);
      }

      console.log(result);
  });

  

Wrap up

There is no shortage of REST clients in the NPM repository, but it's always good to know how to do the lower level stuff yourself.