ExpressJs Router Tutorial

Express is one of the popular web framework for Node.js. It provides wrapper to very useful functionality such as Rendering, Routing etc. In this tutorial i am going to cover Router() in Express framework.

Express router is a class which helps us to create router handlers. By router handler i mean to not just providing routing to our app but also can extend this routing to handle validation, handle 404 or other errors etc.

Our sample project :

To demo the usage of Routing in Express i am going to cover following points step by step. At the end you will have complete code covering all scenarios.

  1. Basic routing.
  2. Basic middleware routing.
  3. Accessing parameter in routing.
  4. Handling 404 errors.
  5. Sample routes for application.

Let’s start :

Package.json :

Here is our sample package.json file.

package.json
{
  "name": "expressRouter",
  "version": "0.0.1",
  "scripts": {
    "start": "node Server.js"
  },
  "dependencies": {
    "express": "^4.12.3"
  }
}

Save the package file and install express dependency using following command.

npm install

Here is our Server file.

Server.js
var express = require("express");
var app = express();

//Creating Router() object

var router = express.Router();

// Provide all routes here, this is for Home page.

router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});

// Tell express to use this router with /api before.
// You can put just '/' if you don't want any sub path before routes.

app.use("/api",router);

// Listen to this Port

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Run this file by typing following command.

npm start

This “start” will trigger “node Server.js” command internally. It’s just cleaner.

You should see following message on Terminal.

Node server

Open any Rest simulator ( Codeforgeek recommends PostMan ) and hit following URL.

http://localhost:3000/api/

You should see below message.

Hello World

Let’s move to using Middle-ware for same.

Basic middleware routing :

Middleware – as the name implies will be executed before your routes get invoked. There are many possible usage for using Middleware for routes such as to log every request before its invoked or finding out whether request is proper or not.

Let’s define one simple Middleware which will print the type of Request ( GET, POST etc ).

Server.js
var express = require("express");
var app = express();

//Creating Router() object

var router = express.Router();

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

// Provide all routes here, this is for Home page.

router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});

// Tell express to use this router with /api before.
// You can put just '/' if you don't want any sub path before routes.

app.use("/api",router);

// Listen to this Port

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Run the app and you hit the API request. You will see following in console.

Screen Shot 2015-05-12 at 10.13.05 PM

next() function will take your router to next routes.

Accessing parameter in Routing :

Before explaining this scenario, let me show you how routes with params look like.

Route : http://example.com/api/:name/
Route with data : http://example.com/api/shahid/

So name – > shahid. Now we can access this params in Route as well as on Middleware. Let me show you both.

Case 1: Accessing it in Middleware.

Assuming the param name is “id”.

// This middle-ware will get the id param
// check if its 0 else go to next router.
router.use("/user/:id",function(req,res,next){
  if(req.params.id == 0) {
    res.json({"message" : "You must pass ID other than 0"});    
  }
  else next();
});

Case 2: Accessing it in Router.

router.get("/user/:id",function(req,res){
  res.json({"message" : "Hello "+req.params.id});
});

Here is complete code.

Server.js
var express = require("express");
var app = express();

//Creating Router() object

var router = express.Router();

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

router.use("/user/:id",function(req,res,next){
  console.log(req.params.id)
  if(req.params.id == 0) {
    res.json({"message" : "You must pass ID other than 0"});    
  }
  else next();
});

// Provide all routes here, this is for Home page.

router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});

router.get("/user/:id",function(req,res){
  res.json({"message" : "Hello "+req.params.id});
});

// Tell express to use this router with /api before.
// You can put just '/' if you don't want any sub path before routes.

app.use("/api",router);

// Listen to this Port

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Run this code and hit following url. http://localhost:3000/api/user/shahid, then replace shahid with 0.

Screen Shot 2015-05-12 at 10.14.19 PM

Now try it with passing 0 and error message will be returned from Middleware not route.

Screen Shot 2015-05-12 at 10.17.37 PM

Handling 404 errors :

404 is error when nothing found for that particular route. To do this we need to put one middle-ware at then end of all routes which will get executed when none of the routes match. Here is a code to do so.

Server.js
var express = require("express");
var app = express();

//Creating Router() object

var router = express.Router();

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

router.use("/user/:id",function(req,res,next){
  console.log(req.params.id)
  if(req.params.id == 0) {
    res.json({"message" : "You must pass ID other than 0"});    
  }
  else next();
});

// Provide all routes here, this is for Home page.

router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});

router.get("/user/:id",function(req,res){
  res.json({"message" : "Hello "+req.params.id});
});

// Handle 404 error.
// The last middleware.
app.use("*",function(req,res){
  res.status(404).send('404');
});

// Tell express to use this router with /api before.
// You can put just '/' if you don't want any sub path before routes.

app.use("/api",router);

// Listen to this Port

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Run this code and try hitting some random route. You should get following output.

Screen Shot 2015-05-12 at 10.21.33 PM

Sample routes for application:

Server.js
var express = require("express");
var app = express();
var router = express.Router();

router.use(function (req,res,next) {
  console.log("/" + req.method);
  next();
});

router.use("/user/:id",function(req,res,next){
  console.log(req.params.id)
  if(req.params.id == 0) {
    res.json({"message" : "You must pass ID other than 0"});
  }
  else next();
});

router.get("/",function(req,res){
  res.sendFile(__dirname + "/public/index.html");
});

router.get("/about",function(req,res){
  res.sendFile(__dirname + "/public/about.html");
});


router.get("/user/:id",function(req,res){
  res.json({"message" : "Hello "+req.params.id});
});

app.use("/",router);

app.use("*",function(req,res){
  res.sendFile(__dirname + "/public/404.html");
});

app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Run this code and visit home page i.e “/” and “/about”. Here i am attaching 404 error page response on browser.

Screen Shot 2015-05-12 at 10.24.26 PM

Conclusion :

You can use Express router to define and extend routing facility for your application. Router will not just help you to just organise and control the routes but also you can use multiple behaviour for same route depending upon HTTP method.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126