Making Http Requests with Node

GET Request

GET request are fairly simple, you can use the http class to make requests. Using http.request will create an instance of ClientRequest and will return an instance of ServerResponse.

(function() {

  var options
    , callback
    , req;

  options = {
    host: '192.168.0.152',
    port: '2345',
    path: '/?derp=turkey',
    method: 'GET'
  }

  callback = function(res) {
    var data = '';
    res.on('data', function(chunk) {
      data+=chunk;
    });
    res.on('end', function() {
      console.log('GET: ' + data);
    });
  };

  req = http.request(options, callback);
  req.end();

}());

POST Request

When making a POST request, you will need to include both data and header params signifying the size of the data you are sending.

(function() {

  var dataString
    , options
    , callback
    , req;

  dataString = querystring.stringify({
    derp : 'turkey'
  });

  options = {
    host: '192.168.0.152',
    port: '2345',
    path: '/',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(dataString)
    }
  };

  callback = function(res) {
    var resOutput = '';
    res.on('data', function(chunk) {
      resOutput += chunk;
    });
    res.on('end', function() {
      console.log('POST: ' + resOutput);
    });
  };

  req = http.request(options, callback);
  req.write(dataString);
  req.end();

}());

Request

An alternative to this code is using the request package. This package greatly simplifies the code needed to make simple HTTP and HTTPS requests.

var sendPostRequest function(requestUri, formData, headers, cb) {  
  var requestOptions,
      handleResponse;

  requestOptions = {
    url: requestUri,
    method: 'POST',
    form: formData,
    headers: headers
  }

  handleResponse = function(err, response, body) {
      if(err) {
       cb(new Error(err));
       return;
    }    
    cb(null, body);
  }

  request(requestOptions, handleResponse);
}
comments powered by Disqus