Thursday, March 29, 2012

NodeJS Http Request That Supports Predefined Headers

Here is another code example on how to create a Http Request function that enables you to predefined the values inside the header of your http request while still maintaining.

Prerequisite

  • Awesome knowledge of NodeJS
  • Reason to use NodeJS's HTTP.Request
  • SublimeText to get awesome view of the codes below

There are two ways on doing this, one with the help of "underscore" library and second is without it.

With Underscore Library


Install this wonderful library with NPM (Node Package Manager)
npm install underscore
Add this on your dependencies section (often on the top of your script page)
var _ = require("underscore");
And this wherever you want
var httpRequest = function(link, headers, body) {

  // remove this if you already used it on the dependencies section
  var url = require("url"), http = require("http");

  // Parse the link so it will become a URL object
  link = url.parse(link);

  // generate the options which will be used by the Http.Request later on
  var options = {
      host : link.hostname
    , port : link.port ? link.port : link.protocol == "https:" ? 443 : 80
    , path : link.path
  }
 
  // Predefined the headers (you can change it anyway you want)
  options.headers = {
      host : link.hostname
    , 'user-agent' : 'Your User Agent Here'
    , 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
    , 'Accept-Language' : 'en-GB,en-US;q=0.8,en;q=0.6'
    , 'content-length' : body ? body.length : ""
  }

  // Extend the Options's Headers so that we can add in custom headers
  if (headers) _.extend(options.headers, headers);

  // Remove empty headers to reduce bandwidth and unwanted errors
  for (var element in options.headers) 
    if (!!!options.headers[element]) 
      delete options.headers[element];

  // Request the data (Http.Request)
  var request = http.request(options, function(response) {
    
    // This event will be triggered on arrival of data
    response.on("data", function(data) {
      // more code here.
    });

    // This event will be triggered on response finished
    response.on("end", function(err) {
      // more code here.
    });

  });

  // This will be triggered if any errors occurred while requesting
  // you can use this to handle unwanted errors
  request.error(function(error) {
    // more code here.
  });

  // End the request to make NodeJS start requesting
  // It will request depending on the body we specified
  request.end(body ? body : "");

}

Without Underscore Library


Just change a part of the above code from
if (headers) _.extend(options.headers, headers);
To
if (headers) for (var element in headers) option.headers[element] = headers[element];

That's it! Enjoy! If you have anything in your mind, just leave it on the comment section below.


Further Readings:

No comments:

Post a Comment