Express Application

A simple and small practical server built using Express. To begin, the variable app is initialized by calling the express() function from the express library. The require command instructs Node to import the library express and assign it to a local variable (also called express).

   var express = require('express');
   var app = express();
     app.get('/books/:name?', function(req, res, next) {
        var name =;
        switch ( name ? name.toLowerCase() : '' ) {
         case 'node':
         case 'mongo':
         case 'javascript':
         res.send(name + ' is my favorite book.');
    app.get('/books/*?', function(req, res){
      res.send('no books listed');

   app.get('/?', function(req, res){
     res.send('hello world');

   var port = 3000;
   console.log('Listening on port ' + port);

The three routes which i defined are :
Expecting the name of one of the books as input
A fallback from the previous route, in case the name provided was not found
A default route used to access the application’s home page.

In the first route, Express is instructed to compare the name of the book provided and print a message if the name is ‘node’, ‘mongo’, or ‘javascript’. In the next route, Express displays a message stating simply that no books are listed, and in the third route, a default ‘hello world’ message is displayed.

The parameter next refers to a function. The next command instructs Express to try processing the next route matching the current request. In this example, entering the URL /books/ is intercepted by the first defined route (/books/:name?) rather than the second (/books). Since there was no name supplied, the logic will fall through to the default case in the switch statement at which point the next() function will be called. The next route (/books) contains the expected response.The question mark after the :name parameter indicates that the name is an optional input—this route will load even if no name is provided.


My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Express, Node.Js Tagged with: ,