HTTP Methods

HTTP is not only about the path, we also have to think about the HTTP methods. In this section, we will enhance our app to handle the different HTTP methods: GET, POST, PUT, and DEL TE.

As the first step towards this, we will add the ability to add different handlers for different methods. We will add the methods in the mapping in resources.js, which is a minor change. This is shown in the following code snippet:

var http = require("http");
var url = require("url");
var route = {
  routes : {}, 
  for: function(method, path, handler){
    this.routes[method + path] = handler;
  }
}

  route.for("GET", "/start", function(request, response){
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello");
    response.end();
  });

  route.for("GET", "/finish", function(request, response){
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Goodbye");
    response.end();
  });

function onRequest(request, response) {
  var pathname = url.parse(request.url).pathname;
  console.log("Request for " + request.method + pathname +" received.");
  if(typeof(route.routes[request.method +pathname])==='function'){
    route.routes[request.method + pathname](request, response);
  }else{
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.end("404 Not Found");
  }
}

http.createServer(onRequest).listen(9999);
console.log("Server has started.");

Save the file and execute with Node.js. The functionality still remains the same, but we will be able to handle different methods using different handlers. Let us create a new handler to echo the incoming data on POST.

  route.on("POST", "/echo", function(request, response){
    var incoming = "";
    request.on('data', function(chunk) {
      incoming += chunk.toString();
    });

    request.on('end', function(){
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write(incoming);
      response.end();
    });
  });

Here we are adding a new handler for the POST request on the /echo path. We again see the use of the event-driven approach of Node.js, this time in handling the data that comes in with POST. Since request is an event emitter, we attach an event handler to it for each task: for handling chunks of incoming data and for completing the request processing once all the data is received.

    request.on('data', function(chunk) {
      incoming += chunk.toString();
    });

In the previous piece of code, we add a listener on the request to handle chunks of incoming data. In this case, all we do is accumulate the incoming data.

    request.on('end', function(){
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write(incoming);
      response.end();
    });

The event handler on end will be invoked once all the data sent in POST has been received. This is the time at which we finish receiving all the data. To build an echo service, we will send back all the accumulated data. We will now create a form to post the request to this handler.

  route.on("GET", "/echo", function(request, response){
    var body = '<html>' + 
    '<head><title>Node.js Echo</title></head>' + 
    '<body>' + 
    '<form method="POST">' + 
    '<input type="text" name="msg"/>' + 
    '<input type="submit" value="echo"/>' + 
    '</form>' + 
    '</body></html>';

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
  });

We will add an event handler to the same path (/echo), but this time, to handle a GET request. In the handler, we will return an HTML page with a form to post to the same path.

Add these two handlers to our route-handlers.js and execute it with Node.js. To open our form, go to http://localhost:9999/echo; then, to trigger our handler, type in a message in the form's textbox and click on the echo button. This will post the content of the form, and in response we will see msg=<your text> in the browser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset