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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Mayank Tyagi
Mayank is a bright Web Developer with expertise in Java language.