a blog for those who code

Thursday 10 September 2015

How to set up router in NodeJS

In this post we are going to discuss about setting up router in NodeJS. Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI and a specific HTTP request method. URI (Uniform Resource Identifier) should be there in order to deliver web content.

Lets first create a server (Create Http server for running nodejs):

var http = require('http');
http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/html'});
  response.end('Hello World !!!');

Now if you run http://localhost:8095/ on a web browser you can see "Hello World !!!". Now say you want to go to about section and you typed http://localhost:8095/about this path will also render "Hello World !!!" itself because routing is not in place. So lets start building some routing. At first we will create a section which we want like about, privacy etc. the we will refer that section in our code.

var section = [
    {route: '', content: 'Hello World !!!'},
    {route: 'about', content: 'This is about section'},
    {route: 'privacy', content: 'This is privacy section'}

var http = require('http');
var path = require('path');
http.createServer(function(request, response) {
  var curSection = path.basename(decodeURI(request.url));
  section.forEach(function(sec) {
    if(sec.route === curSection) {
      response.writeHead(200, {'Content-Type': 'text/html'});

The above code is getting the current section (basename) from the line var curSection = path.basename(decodeURI(request.url)); After that we are checking the current section from the list of sections and if the section is there we are just showing the content of that section on the webpage. If you go to http://localhost:8095/about it will show "This is about section" and if you go to http://localhost:8095/privacy it will show "This is privacy section".

If you do not want to set up routing in the above way then you can use some of the routing modules like :

1. express - Fast, unopinionated, minimalist web framework
2. director - A client Side/Sever Side Router
3. bouncy - Route incoming http requests to http servers
4. page - Tiny client-side router
5. crossroads - Flexible router which can be used in multiple environments
6. mapleTree - Simple routing library for node.js
7. connect_router - The original router from connect 1.x - the High performance middleware framework
8. beeline - A laughably simplistic router for node.js
9. biggie-router - A lightweight extensible HTTP router
10. router - Simple middleware-styl helpful.

Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment