How to use Router in NodeJS

Posted By : Mayank Tyagi | 31-Mar-2015

To use router in our code first step is to install the router using npm command to install the router is:

 npm install router
 

Now we can use router in our NodeJS code . The simple code to demonstrate the use of router is:

 var myRouter=require('router')
var router=myRouter();
router.get('/',function(req,res){
      res.end("hello world")
}).listen(9090);
 

In the above program we have used router to be work on '/' when there is call on '/' the response will end with hello world and the server will listen this request on the port 9090 in case you want to use the router for another url then you can change the '/' to '/home' or whatever url you want to append in that

Using router.param:-

Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. It maps the specified paths parameter name to the param capturing middleware

 router.param('user_id', function (req, res, next, id) {
  User.find(id, function (err, user) {
    if (err) {
      return next(err)
    } else if (!user) {
      return next(new Error('user cannot be loaded'))
    }
    req.user = user
 
    // continue processing the request 
    next()
  })
})
 

Using router.route:-

To handle the http request in the program we can use routes

var api = router.route('/api/version/user')
 

using router.route:- We can avoid duplicate route request .So in case of duplicate route situation its better to use the route to handle the http request Using routes

Using route.all:- we can add handler to all http method to this route

 router.route('/')
.all(function (req, res, next) {
  next()
})
.all(check_something)
.get(function (req, res) {
  res.end('hello to all ')
})
 
  

Thanks and Regards

Mayank Tyagi

About Author

Author Image
Mayank Tyagi

Mayank is a bright Web Developer with expertise in Java language.

Request for Proposal

Name is required

Comment is required

Sending message..