Building Web Applications Using Node.js - Part Three

Before reading this article, I recommend you read my previous articles.
In my previous two articles, I have explained -
  • How to start working with node.js web application
  • How to initialize a node.js project
  • About Package.json
  • Express Framework
  • How to use "npm start" command
  • Using HTML Templates
  • Bower
  • Templating Engine
Now, in this article, I will explain to you how we can create the Navigation menu dynamically. Then, we will perform routing using navigation, and then we will render our page. After that, we will separate our sections and many more.
 
So, I am opening index.ejs file which I have created in my last article and copying the complete HTML code from my index.html file into index.ejs file.
 
index.ejs
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   
  4. <head>  
  5.   
  6.     <meta charset="utf-8">  
  7.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  8.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.     <meta name="description" content="">  
  10.     <meta name="author" content="">  
  11.   
  12.     <title>1 Col Portfolio - Start Bootstrap Template</title>  
  13.   
  14.     <!-- Bootstrap Core CSS -->  
  15.     <link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">  
  16.   
  17.     <!-- Custom CSS -->  
  18.     <link href="css/1-col-portfolio.css" rel="stylesheet">  
  19.   
  20.     <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->  
  21.     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->  
  22.     <!--[if lt IE 9]>  
  23.         <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>  
  24.         <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>  
  25.     <![endif]-->  
  26.   
  27. </head>  
  28.   
  29. <body>  
  30.   
  31.     <!-- Navigation -->  
  32.     <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">  
  33.         <div class="container">  
  34.             <!-- Brand and toggle get grouped for better mobile display -->  
  35.             <div class="navbar-header">  
  36.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">  
  37.                     <span class="sr-only">Toggle navigation</span>  
  38.                     <span class="icon-bar"></span>  
  39.                     <span class="icon-bar"></span>  
  40.                     <span class="icon-bar"></span>  
  41.                 </button>  
  42.                 <a class="navbar-brand" href="#">Start Bootstrap</a>  
  43.             </div>  
  44.             <!-- Collect the nav links, forms, and other content for toggling -->  
  45.             <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">  
  46.                 <ul class="nav navbar-nav">  
  47.                     <li>  
  48.                         <a href="#">About</a>  
  49.                     </li>  
  50.                     <li>  
  51.                         <a href="#">Services</a>  
  52.                     </li>  
  53.                     <li>  
  54.                         <a href="#">Contact</a>  
  55.                     </li>  
  56.                 </ul>  
  57.             </div>  
  58.             <!-- /.navbar-collapse -->  
  59.         </div>  
  60.         <!-- /.container -->  
  61.     </nav>  
  62.   
  63.     <!-- Page Content -->  
  64.     <div class="container">  
  65.   
  66.         <!-- Page Heading -->  
  67.         <div class="row">  
  68.             <div class="col-lg-12">  
  69.                 <h1 class="page-header">Page Heading  
  70.                     <small>Secondary Text</small>  
  71.                 </h1>  
  72.             </div>  
  73.         </div>  
  74.         <!-- /.row -->  
  75.   
  76.         <!-- Project One -->  
  77.         <div class="row">  
  78.             <div class="col-md-7">  
  79.                 <a href="#">  
  80.                     <img class="img-responsive" src="http://placehold.it/700x300" alt="">  
  81.                 </a>  
  82.             </div>  
  83.             <div class="col-md-5">  
  84.                 <h3>Project One</h3>  
  85.                 <h4>Subheading</h4>  
  86.                 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium veniam exercitationem expedita laborum at voluptate. Labore, voluptates totam at aut nemo deserunt rem magni pariatur quos perspiciatis atque eveniet unde.</p>  
  87.                 <a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>  
  88.             </div>  
  89.         </div>  
  90.         <!-- /.row -->  
  91.   
  92.         <hr>  
  93.   
  94.         <!-- Project Two -->  
  95.         <div class="row">  
  96.             <div class="col-md-7">  
  97.                 <a href="#">  
  98.                     <img class="img-responsive" src="http://placehold.it/700x300" alt="">  
  99.                 </a>  
  100.             </div>  
  101.             <div class="col-md-5">  
  102.                 <h3>Project Two</h3>  
  103.                 <h4>Subheading</h4>  
  104.                 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut, odit velit cumque vero doloremque repellendus distinctio maiores rem expedita a nam vitae modi quidem similique ducimus! Velit, esse totam tempore.</p>  
  105.                 <a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>  
  106.             </div>  
  107.         </div>  
  108.         <!-- /.row -->  
  109.   
  110.         <hr>  
  111.   
  112.         <!-- Project Three -->  
  113.         <div class="row">  
  114.             <div class="col-md-7">  
  115.                 <a href="#">  
  116.                     <img class="img-responsive" src="http://placehold.it/700x300" alt="">  
  117.                 </a>  
  118.             </div>  
  119.             <div class="col-md-5">  
  120.                 <h3>Project Three</h3>  
  121.                 <h4>Subheading</h4>  
  122.                 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis, temporibus, dolores, at, praesentium ut unde repudiandae voluptatum sit ab debitis suscipit fugiat natus velit excepturi amet commodi deleniti alias possimus!</p>  
  123.                 <a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>  
  124.             </div>  
  125.         </div>  
  126.         <!-- /.row -->  
  127.   
  128.         <hr>  
  129.   
  130.         <!-- Project Four -->  
  131.         <div class="row">  
  132.   
  133.             <div class="col-md-7">  
  134.                 <a href="#">  
  135.                     <img class="img-responsive" src="http://placehold.it/700x300" alt="">  
  136.                 </a>  
  137.             </div>  
  138.             <div class="col-md-5">  
  139.                 <h3>Project Four</h3>  
  140.                 <h4>Subheading</h4>  
  141.                 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Explicabo, quidem, consectetur, officia rem officiis illum aliquam perspiciatis aspernatur quod modi hic nemo qui soluta aut eius fugit quam in suscipit?</p>  
  142.                 <a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>  
  143.             </div>  
  144.         </div>  
  145.         <!-- /.row -->  
  146.   
  147.         <hr>  
  148.   
  149.         <!-- Project Five -->  
  150.         <div class="row">  
  151.             <div class="col-md-7">  
  152.                 <a href="#">  
  153.                     <img class="img-responsive" src="http://placehold.it/700x300" alt="">  
  154.                 </a>  
  155.             </div>  
  156.             <div class="col-md-5">  
  157.                 <h3>Project Five</h3>  
  158.                 <h4>Subheading</h4>  
  159.                 <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, quo, minima, inventore voluptatum saepe quos nostrum provident ex quisquam hic odio repellendus atque porro distinctio quae id laboriosam facilis dolorum.</p>  
  160.                 <a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>  
  161.             </div>  
  162.         </div>  
  163.         <!-- /.row -->  
  164.   
  165.         <hr>  
  166.   
  167.         <!-- Pagination -->  
  168.         <div class="row text-center">  
  169.             <div class="col-lg-12">  
  170.                 <ul class="pagination">  
  171.                     <li>  
  172.                         <a href="#">«</a>  
  173.                     </li>  
  174.                     <li class="active">  
  175.                         <a href="#">1</a>  
  176.                     </li>  
  177.                     <li>  
  178.                         <a href="#">2</a>  
  179.                     </li>  
  180.                     <li>  
  181.                         <a href="#">3</a>  
  182.                     </li>  
  183.                     <li>  
  184.                         <a href="#">4</a>  
  185.                     </li>  
  186.                     <li>  
  187.                         <a href="#">5</a>  
  188.                     </li>  
  189.                     <li>  
  190.                         <a href="#">»</a>  
  191.                     </li>  
  192.                 </ul>  
  193.             </div>  
  194.         </div>  
  195.         <!-- /.row -->  
  196.   
  197.         <hr>  
  198.   
  199.         <!-- Footer -->  
  200.         <footer>  
  201.             <div class="row">  
  202.                 <div class="col-lg-12">  
  203.                     <p>Copyright © Your Website 2014</p>  
  204.                 </div>  
  205.             </div>  
  206.             <!-- /.row -->  
  207.         </footer>  
  208.   
  209.     </div>  
  210.     <!-- /.container -->  
  211.   
  212.     <!-- jQuery -->  
  213.     <script src="lib/jquery/dist/jquery.js"></script>  
  214.   
  215.     <!-- Bootstrap Core JavaScript -->  
  216.     <script src="lib/bootstrap/dist/js/bootstrap.min.js"></script>  
  217.   
  218. </body>  
  219.   
  220. </html>  
So, now my index.ejs file output looks like the following.

 
First of all, I am going to create the navigation menu bar dynamically as well as I am also changing the title of the page. To do that, I am modifying the app.js file and writing the following code.
  1. app.get('/',function(req,res){  
  2.     res.render('index', {  
  3.         title:'Node.js By Sourabh Somani',  
  4.         menu:[  
  5.             {  
  6.                 href:'/articles',  
  7.                 text:'Article'  
  8.             },  
  9.             {  
  10.                 href:'/projects',  
  11.                 text:'Projects'  
  12.             },  
  13.             {  
  14.                 href:'/books',  
  15.                 text:'books'  
  16.             },  
  17.             {  
  18.                 href:'/contact',  
  19.                 text:'Contact Us'  
  20.             },  
  21.         ]  
  22.     });  
  23. });  
Now, I am going to modify the index.ejs file and writing the code for dynamic navigation menu and page title.
 
For title, I am writing the following line of code.
  1. <title><%=title%></title>  
For navigation menu, I am writing the following line of code.
  1. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">  
  2.     <ul class="nav navbar-nav">  
  3.         <%for(var i=0;i<menu.length;i++){%>  
  4.         <li>  
  5.             <a href="<%=menu[i].href%>"><%=menu[i].text%></a>  
  6.         </li>  
  7.         <%}%>  
  8.     </ul>  
  9. </div>  
Now, when I run my project, my output will be like as follows.



I am also changing the logo text, using the following line of code.
  1. <a class="navbar-brand" href="/">Node.js Web App</a>  
Output

 
Now, I am going to use routing using Express Router function. Previously, it was routing using app.get function but now, we will do it by using Router. So, I am going to change my "app.js" file.
 
First of all create router variables.
  1. //routing using Router  
  2. var articlesRouter=express.Router();  
  3. var projectsRouter=express.Router();  
  4. var booksRouter=express.Router();  
  5. var contactRouter=express.Router();   
Now, define routing for each router, like the following.
  1. //Defining Routes  
  2. articlesRouter.route("/");  
  3. projectsRouter.route("/");  
  4. booksRouter.route("/");  
  5. contactRouter.route("/");   
Now, we have to tell our application which router will be used for each different routes. To do that, write the code as shown below.
  1. app.use('/articles',articlesRouter);  
  2. app.use('/projects',projectsRouter);  
  3. app.use('/books',booksRouter);  
  4. app.use('/contact',contactRouter);   
So, the above line of code will tell our application that when request comes from /articles, then use articlesRouter; when request comes from /projects, then use projectsRouter; when request comes from /books, then use booksRouter; and when request comes from /contact, then use contactRouter.

app.js Complete code
  1. var express=require('express');  
  2. var app=new express();  
  3. var port=3000;  
  4. app.listen(port,function(err){  
  5.     if(typeof(err)=="undefined"){  
  6.         console.log('Your application is running on : '+ port+' port');  
  7.     }  
  8. });  
  9. //routing using Router  
  10. var articlesRouter=express.Router();  
  11. var projectsRouter=express.Router();  
  12. var booksRouter=express.Router();  
  13. var contactRouter=express.Router();  
  14.   
  15. app.use(express.static('public'));//making public directory as static diectory   
  16.   
  17. app.set('views','./src/views');   
  18.   
  19. app.set('view engine','ejs');  
  20.   
  21. articlesRouter.route("/");  
  22. projectsRouter.route("/");  
  23. booksRouter.route("/");  
  24. contactRouter.route("/");  
  25.   
  26. app.use('/articles',articlesRouter);  
  27. app.use('/projects',projectsRouter);  
  28. app.use('/books',booksRouter);  
  29. app.use('/contact',contactRouter);  
  30.   
  31. app.get('/',function(req,res){  
  32.     res.render('index', {  
  33.         title:'Node.js By Sourabh Somani',  
  34.         menu:[  
  35.             {  
  36.                 href:'/articles',  
  37.                 text:'Article'  
  38.             },  
  39.             {  
  40.                 href:'/projects',  
  41.                 text:'Projects'  
  42.             },  
  43.             {  
  44.                 href:'/books',  
  45.                 text:'Books'  
  46.             },  
  47.             {  
  48.                 href:'/contact',  
  49.                 text:'Contact Us'  
  50.             },  
  51.         ]  
  52.     });  
  53. });  
Output

  
Now, I am going to create different views for different routing respectively. So, I am creating 4 EJS files in Views folder. 

 
 
Now, in all files, I am copying the code from index.ejs and pasting it in all files. After pasting all this code, I am going to render all the views which I have created from "app.js" file.
 
Rendering articles route
  1. articlesRouter.route("/")  
  2.     .get(function(req,res){  
  3.         res.render('articles', {  
  4.             title:'Articles',  
  5.             menu:navMenu  
  6.         });  
  7.     });  
Rendering projects route
  1. projectsRouter.route("/")  
  2.     .get(function(req,res){  
  3.         res.render('projects', {  
  4.             title:'Projects',  
  5.             menu:navMenu  
  6.         });  
  7.     });  
Rendering books route
  1. booksRouter.route("/")  
  2.     .get(function(req,res){  
  3.         res.render('books', {  
  4.             title:'Books',  
  5.             menu:navMenu  
  6.         });  
  7.     });   
Rendering contact route
  1. contactRouter.route("/")  
  2.     .get(function(req,res){  
  3.         res.render('contact', {  
  4.             title:'Contact Us',  
  5.             menu:navMenu  
  6.         });  
  7.     });  
Above, you can see that I am using menu as navMenu, so I have created an array for navMenu. Which looks like the following.
  1. //Navigation Menu  
  2. var navMenu=[  
  3.                 {  
  4.                     href:'/articles',  
  5.                     text:'Articles'  
  6.                 },  
  7.                 {  
  8.                     href:'/projects',  
  9.                     text:'Projects'  
  10.                 },  
  11.                 {  
  12.                     href:'/books',  
  13.                     text:'Books'  
  14.                 },  
  15.                 {  
  16.                     href:'/Contact',  
  17.                     text:'Contact Us'  
  18.                 },  
  19.             ];   
 Now, run your project and click on menu bar. You will get the following output.
 
Output of Home page


Output of Articles page

 
Output of Projects page

 

Output of Books page

 
Output of Contact page

 
 
 
Now, you can see that we have written all the code inside one file that is "app.js" and when we create project, we always separate our files. We do not write code in only one file because that will make the file very complicated to understand.
 
So now, we are going to separate routing files in different folders. Let's create one folder named as "routes" in src directory where all routing files will be located.
 
So, in this folder, I am going to create several JS file for routing.

 
 
Now, I am writing the following code in each file.

articlesRoute.js
  1. var express=require('express');  
  2.   
  3. var articlesRouter=express.Router();  
  4. var navMenu=[  
  5.                 {href:'/articles',text:'Articles'},  
  6.                 {href:'/projects',text:'Projects'},  
  7.                 {href:'/books',text:'Books'},  
  8.                 {href:'/Contact',text:'Contact Us'}  
  9.            ];   
  10. articlesRouter.route("/")  
  11.     .get(function(req,res){  
  12.         res.render('articles', {  
  13.             title:'Articles',  
  14.             menu:navMenu  
  15.         });  
  16.     });  
  17.   
  18. module.exports=articlesRouter;  
projectsRoute.js
  1. var express=require('express');  
  2.   
  3. var projectsRouter=express.Router();  
  4. var navMenu=[  
  5.                 {href:'/articles',text:'Articles'},  
  6.                 {href:'/projects',text:'Projects'},  
  7.                 {href:'/books',text:'Books'},  
  8.                 {href:'/Contact',text:'Contact Us'}  
  9.            ];   
  10. projectsRouter.route("/")  
  11.     .get(function(req,res){  
  12.         res.render('projects', {  
  13.             title:'Projects',  
  14.             menu:navMenu  
  15.         });  
  16.     });  
  17.   
  18. module.exports=projectsRouter;  
booksRoute.js 
  1. var express=require('express');  
  2.   
  3. var booksRouter=express.Router();  
  4. var navMenu=[  
  5.                 {href:'/articles',text:'Articles'},  
  6.                 {href:'/projects',text:'Projects'},  
  7.                 {href:'/books',text:'Books'},  
  8.                 {href:'/Contact',text:'Contact Us'}  
  9.            ];   
  10. booksRouter.route("/")  
  11.     .get(function(req,res){  
  12.         res.render('books', {  
  13.             title:'Books',  
  14.             menu:navMenu  
  15.         });  
  16.     });  
  17.       
  18. module.exports=booksRouter;  
contactRoute.js  
  1. var express=require('express');  
  2.   
  3. var contactRouter=express.Router();  
  4. var navMenu=[  
  5.                 {href:'/articles',text:'Articles'},  
  6.                 {href:'/projects',text:'Projects'},  
  7.                 {href:'/books',text:'Books'},  
  8.                 {href:'/Contact',text:'Contact Us'}  
  9.            ];   
  10. contactRouter.route("/")  
  11.     .get(function(req,res){  
  12.         res.render('contact', {  
  13.             title:'Contact Us',  
  14.             menu:navMenu  
  15.         });  
  16.     });  
  17.   
  18. module.exports=contactRouter;   
 Remove the old routing code from app.js file and use routing as following.
  1. var articlesRouter=require('./src/routes/articlesRoute');  
  2. var projectsRouter=require('./src/routes/projectsRoute');  
  3. var booksRouter=require('./src/routes/booksRoute');  
  4. var contactRouter=require('./src/routes/contactRoute');  
Complete app.js code
  1. var express=require('express');  
  2. var app=new express();  
  3. var port=3000;  
  4. app.listen(port,function(err){  
  5.     if(typeof(err)=="undefined"){  
  6.         console.log('Your application is running on : '+ port+' port');  
  7.     }  
  8. });  
  9.   
  10. app.use(express.static('public'));//making public directory as static diectory   
  11.   
  12. app.set('views','./src/views');   
  13.   
  14. app.set('view engine','ejs');  
  15.   
  16. var articlesRouter=require('./src/routes/articlesRoute');  
  17. var projectsRouter=require('./src/routes/projectsRoute');  
  18. var booksRouter=require('./src/routes/booksRoute');  
  19. var contactRouter=require('./src/routes/contactRoute');   
  20.   
  21. var express=require('express');  
  22.   
  23. var articlesRouter=express.Router();  
  24. var navMenu=[  
  25.                 {href:'/articles',text:'Articles'},  
  26.                 {href:'/projects',text:'Projects'},  
  27.                 {href:'/books',text:'Books'},  
  28.                 {href:'/Contact',text:'Contact Us'}  
  29.            ];   
  30. articlesRouter.route("/")  
  31.     .get(function(req,res){  
  32.         res.render('articles', {  
  33.             title:'Articles',  
  34.             menu:navMenu  
  35.         });  
  36.     });  
  37.   
  38. module.exports=articlesRouter;  
  39.   
  40. app.use('/articles',articlesRouter);  
  41. app.use('/projects',projectsRouter);  
  42. app.use('/books',booksRouter);  
  43. app.use('/contact',contactRouter);  
  44.   
  45. app.get('/',function(req,res){  
  46.     res.render('index', {  
  47.         title:'Node.js By Sourabh Somani',  
  48.         menu:navMenu  
  49.     });  
  50. });  
Output
 
Output of Home page


Output of Articles page


Output of Projects page


Output of Books page



Output of Contact page

 
Conclusion

In this article, we have learned
  • How we can render our page and how can we perform routing in Node.js.
  • How to perform navigation.
In the next part of this series, we will see how we can fetch data from the database and bind it to our application.
 
Thanks :)