Routers are very important in any web server. Primary function of a Router is to accept request and on basis of requested URL trigger desired process.
Consider a rough example in that client is requesting
http://abc.com/users/myprofile and there request may serve from URL http://abc.com/node/2 assuming user is stored in node with id 2.
In Node.js you can create router using many publicly available modules. Some of them are as follows,
- Express
- Director
- Bouncy
- Backbone
- Crossroads
In this post let us create a router using Crossroads. To start with install crossroads module in application using npm crossroads or you may want to use mange modules in Visual Studio as well.
Once crossroads module is installed you need to load crossroads module in application.
You can add route in application using addRoute function. I have added route which takes two parameters.
crossroads.addRoute('/{type}/:id:',function(type,id){ if(!id) { result = "Acess informtion about all " + type; return; } else { result = "Acess informtion about "+ type + "with id" +id ; return; } });
In above route
- Type is parameter need to be passed to request server
- Id is optional parameter to be passes to request server. Optional parameters should be enclosed with ::
Second parameter of addRoute is a callback function. In this callback you need to write logic to work with different requests with different parameters in request. As you see in above example we are constructing string on basis of requested URL.
If you write result in response then you will get output as below,
In first request we are passing only type (student) whereas in second request we are passing both type and optional id.
So when adding route you can have parameters in request as
If you want to add a route with REST segment then you can do that as follows,
Now on requesting server you will get id passed as optional REST segment.
Putting all together you can create a Router in Node.js application using crossroad as below,
var http = require('http'); var crossroads = require('crossroads'); var result ; crossroads.addRoute('/{type}/:id*:',function(type,id){ if(!id) { result = "Acess informtion about all " + type; return; } else { result = "Acess informtion about "+ type + "with id" +id ; return; } }); http.createServer(function(request,response){ crossroads.parse(request.url) ; response.writeHead(200); response.write(result); request.on('end',function(){ response.end("Req End"); }); }).listen(8080,function(){ console.log("server started"); });
In above code apart from creating server we are parsing request URL as well using parse function
In this you can create a router. Off course you can use other modules to create router as well. When working with web applications router of express framework is very powerful. I hope you find this post useful. Thanks for reading.
Leave a Reply