Monday, August 15, 2016

Nodejs Route Prefixing in Expressjs


Routing is an important part of modern web applications. we do route for various features development. Routing is actually handling the receiving request and providing response properly. Routing is a getway to receive request from various sources into your application and responding to that request with required data.



When we develop application, specially the web application, Routing is an important issue. we have to handle multiple route, route group. Route grouping is a concept to make the route function that receive same prefix of different requests.

If you come from other frameworks to Nodejs express, maybe you will find to handle same route groups as route prefixing. Here is a simple way to make route prefixing in Nodejs express framework.

Let's create a server.js file



var express = require('express');
var app     = express();
var port    =   process.env.PORT || 8080;

var data = require('./data');

// ROUTES
// ==============================================

express.application.prefix = express.Router.prefix = function (path, configure) {
    var router = express.Router();
    this.use(path, router);
    configure(router);
    return router;
};

var app = express();


// route grouping
app.prefix('/', function (home) {

    home.route('/').get(data.welcome); //other route
    home.route('/home').get(data.home); // other route
   
});


// route group
app.prefix('/cats', function (cats) {

    cats.route('/').get(data.cat);  // other route
    cats.route('/detail').get(data.detail); //other route
   
});

// route group
app.prefix('/dogs', function (dogs) {

    dogs.route('/').get(data.dog);   // other route
    dogs.route('/detail').get(data.detail);  // other route
   
});


// START THE SERVER
// ==============================================
app.listen(port);
console.log('Magic happens on port ' + port);


Next create a data file as data.js


exports.welcome = function(req,res){

 res.send("Welcome to app for route group ");

};

exports.home = function(req,res){

 res.send("Welcome to app home");

};



exports.cat = function(req,res){

 res.send("Welcome to app Cats");

};

exports.dog = function(req,res){

 res.send("Welcome to app dog");

};



exports.detail = function(req,res){

 res.send("This is about detail");


};


Now run the application with node server.js  Your application will run on localhost:8080 . You are now able to see result as


#routes

http://localhost:8080/home

http://localhost:8080/cats

http://localhost:8080/cats/detail

http://localhost:8080/dogs

http://localhost:8080/dogs/detail

The route is being handle from route group. You can get the full source code at github.com for more help. Click here

No comments:

Post a Comment