Node.js: Implementing Routing using Express.js

Posted by: Mahesh Sabnis , on 6/23/2016, in Category Node.js
Views: 25165
Abstract: Use Express.js and Node.js to implement routing on server side to deliver Html pages as well as Data

In this article, we will use Express.js to implement routing on server side to deliver Html pages as well as Data.

Node.js & Express application: The implementation

This application will be implemented using Visual Studio Code (VSCode). VSCode is a new IDE from Microsoft used for developing and debugging modern application. This is a free IDE and can be installed on Windows OS, Linux and MAC OSX. You can download VSCode from this link.

 

Step 1: Create a folder on your machine with the name RoutingUsingExpress. Open VSCode. Using File > Open Folder option, open RoutingUsingExpress. Using VSCode create a new JavaScript file of the name app.js.

Step 2: We need to install Node Intellisense and Express.js for the application. To install these, right click on app.js and select Open in Command Prompt. This will open the command prompt from where we will install the required packages.

Run the following command from the command prompt:

npm install tsd –g

This is a TSD package manager for searching and installing TypeScript definition files. We will use this package for installing Express. We also need TSD to use intellisense in VSCode.

tsd query node --action install

This will install TSD for Node so that we can use its intellisense.

Npm install express
tsd query express --action install

This will install Express using Node Package manager and install the TypeScript definition for Express so that we can use its intellisense in VSCode.

Step 3: In the project, add the Views folder with following three files

  • Home.html
  • About.html
  • Contact.html

Step 4: In app.js, add the following code:

//1.
var express = require('express');
//2.
var path = require('path');
//3.
var app = express();
//4.
var objExpress = express.Router();


//5.
objExpress.get("/", function (request, response) {
    response.sendFile('home.html', { root: path.join(__dirname, './Views') });
});

//6.
objExpress.get('/about', function (request, response) {
    response.sendFile('about.html', { root: path.join(__dirname, './Views') });
});
//7.
objExpress.get('/contact', function (request, response) {
    response.sendFile('contact.html', { root: path.join(__dirname, './Views') });
});
//8.
objExpress.get('/data', function (req, resp) {
    
    var Emp = [
        { 'EmpNo': 101, 'EmpName': "A" },
        { 'EmpNo': 102, 'EmpName': "B" },
    ];
    
    resp.send(Emp);
});
//9.
objExpress.get('/data/:dname', function (req, resp) {
    var id = req.params.dname;
    if (id == 'IT') {
        var Emp = [
            { 'EmpNo': 101, 'EmpName': "A", 'DeptNae': 'IT' },
            { 'EmpNo': 102, 'EmpName': "B" , 'DeptNae': 'IT' },
        ];
        
    } else {
        var Emp = [
            { 'EmpNo': 101, 'EmpName': "C", 'DeptNae': 'Systems' },
            { 'EmpNo': 102, 'EmpName': "D", 'DeptNae': 'Systems' },
        ];
    }
    resp.send(Emp);
});

//10.
app.use(objExpress);
//11.
app.listen(8090, function () {
    console.log('Listening on  port 8090');
});
console.log('Application started....');

 

The above code has the following specifications:

Note: Line numbers below matches with the comments applied on the code.

1. Loads the Express module

2. Loads the path module so that the directory path for html files can be read.

3. Creates an instance of Express object. This will be used to define the port on which incoming http requests will be read.

4. This line calls the Router() function so that functions for route can be defined for http request types (get, post, put, delete, etc.). The instance of the Routing is defined as objExpress.

5. Use the get() function on the Express router object. This accepts two parameters - the first parameter is Route Expression URI and second parameter is the callback which responds with the home.html file in the Views directory.

6. Route expression for about.html

7. Route expression for contact.html.

8. The get() call which has the URL expression ‘/data’. This function is written to respond with an Employee array.

9. The get() call uses /data:dname, URI expression. Here
dname is the parameter which will be passed with Http request in the URL. The get() function will execute based on the value of dname. In the current example, if dname is IT then the if statement will be executed, otherwise else statement will be executed.

10. The use() function loads the router object in Express instance so that it will be used in http requests.

11. Express will start listening on 8090 port using the listen() function.

Step 5: To run the application, enter the following command in the command prompt which can be opened using Step 2.

Node app

The following result will be displayed

node-result

Open the Browser e.g. Chrome and enter the following URL

http://localhost:8090

nodejs-home-page

http://localhost:8090/about

about-page

http://localhost:8090/data

This will show the Employees data as shown in the following image

data-route

http://localhost:8090/data/IT

This will show Employee data with DeptName value as IT:

data-routing

Conclusion:

Express web application in Node.js provides functions using which we can implement routing for responding with html views and data.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!