Tuesday, January 3, 2012

Nodejs with handlers in javascript


We can point site URL to a specific handler, created by nodejs(server side javascript). Hummm, Sounds exceptional. Let’s see.   We are able to create a server in previous post. Have you noticed request and response in the code? Request object contains all the Request properties. URL (string) is one of it. [In previously it was uri(object).]  From the url property we can get the requested url path and according to that we can handle the request as per plan. Pretty simple. Now see the code[written in notepad, you can use any other editor] -

var http = require('http');
var sys = require('util');
 var server = http.createServer(function(req, res) {
  switch (req.url) { //check the request url
    case '/’:
      display_home(req, res); //pointing handler
      break;
    case '/registration’: 
      display_registration (req, res);
      break;
    default:
      show_404(req, res);//no handler found
      break;
  }
});
server.listen(8088);
//====== Server generation and handler pointing is done======
//==========First handler===============
function display_ home (req, res) {
//======response type set=========
  res.writeHead(200, {'Content-Type': 'text/html'});
//=======response content============== 
res.end(
    '<div> This is your home page</div><a  href=”/registration”> Click to register</a><a  href=”/nothing”> nothing</a>'
  );
}
//========Second handler=================
function display_ registration (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(
    '<div> This is your registration page</div>'
  );
}
//==========Error handler==========
function show_404(req, res) {
  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.end('No handler found');
 
}

Save the code with js extension. Run this with node command  as shown in previous post and traverse through your first nodeJs site.
Let me know your quires.
Enjoy.
Post a Comment