Express JS Routings with Enide Studio 2014 IDE

Filed Under: Node.js

This post is a continuation post of my previous post “Express JS WebApplication with Enide Studio 2014 IDE”. In my previous post, we have discussed about “How to create a Express JS WebApplication with Enide Studio 2014 IDE”. We have just created and discussed about some code snippets. We have not discussed about Express JS Routings.

We are going to discuss Express JS Routings in this post in details. Before reading this post “Express JS WebApplication with Enide Studio 2014 IDE”, please refer my previous post and create Express JS WebApplication.

Brief Steps To Create Express JS Routings

Here I’m going to give you the steps to follow to create Routings in Express JS WebApplication. First, We will discuss each step in detail with Enide Studio 2014 IDE Default “Node:Express JS Project”. Then we will discuss about how to create our own Express JS Routings in coming sections.

  • Create Routings
  • Create Views
  • Load all newly created Routing files into Variables in app.js
  • Map Client Requested URLs to Routings in app.js
  • Start Application and Test Routings

Explore Default Express JS Routings

When we create Express JS Sample WebApplication using Enide Studio 2014 IDE, it creates a “app.js” file at Project root directory. This is the starting point to access Express JS Application.

  • First load “express” module into our application cache and create Express JS Application as shown below
  • 
    var express = require('express');
    var app = express();
    
  • It places all Express JS Routing files under “${EXPRESSJS_PROJECT_ROOT_DIR}\routes” folder
  • Our “expressjs” project contains default two routing files: index.js and users.js

  • It places all Express JS View files under “${EXPRESSJS_PROJECT_ROOT_DIR}\views” folder
  • As Default “Node JS: Express JS Project” uses JADE as default Template Engine, it creates jades as views at this location.
    This project contains default three views: index.jade, layoug.jade and error.jade

    NOTE:- JADE is simple and very powerful Template Engine Framework to Design and Develop HTML pages very easily. Please refer some online tutorials on this Framework. I will try to give one to two posts on this JADE framework after sometime.

  • Explore Routings in index.js
  • index.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });
    
    module.exports = router;
    

    Code Explanation

    1. Line 1, Loaded Express JS Module into our application cache and stored it into a variable “express”
    2. Line 2, use Router class to create a router object. We use “express” variable to create Router object: ” express.Router()”
    3. Line 5-7, using “router” object, we have created a function to handle HTTP GET Requests
    4. Line 6, it is very important because here we wrote our Routings. When Client or WebBrowser sends request using “/” (That is http://localhost:3000/) using HTTP GET Request method, then it comes to this function and route the controller to the “index” view. It is automatically mapped to “index.jade” and populate “title” attribute with ‘Express’ value (Please refer below index.jade file).
    5. index.jade

      
      extends layout
      
      block content
        h1= title
        p Welcome to #{title}
      

      That’s why when we access our application using “http://localhost:3000/”, we got the following output showing this “title” attribute value as ‘Express’.

      express_sample_webapp_output

      NOTE:- I guess you all are already familiar with Spring MVC or Struts Frameworks. Even in these frameworks also, we do similar kind of Routings right.

    6. Line 9, we have exported our router object to be used in other modules in the Same or different Projects.
  • Explore Routings in users.js
  • users.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('respond with a resource');
    });
    
    module.exports = router;
    

    It is just duplication of index.js file but it does NOT map to any view here. We are just sending a response text ‘respond with a resource’ to the Client or Browser.

    If we access the same application with “http://localhost:3000/users”, then we will get the following output on Browser:

    expressjs_webapp_users_output

  • Explore app.js
  • Once we have developed both Views and Routes, now it’s time to map them. We need to map them in app.js file. This is very important and staring point for a Node:Express JS application. When we execute “npm start” command from Command Prompt at Project Root Directory, it searches for “app.js” file. Then it loads all project files into Server and waits for Client Requests.

    Now we will see how to map these files in “app.js” file in step by step.

    1. First step is loading our Routing files into variables as shown below
    2. 
      var routes = require('./routes/index');
      var users = require('./routes/users');
      

      Like loading other Node JS Module into our Project Cache, We use require() call to load our Routing files into variables .

    3. Map URLs to these Routing variables as shown below using “app” Express JS Application Object.
    4. 
      app.use('/', routes);
      app.use('/users', users);
      

      That means, when Client or WebBroswer sends request to our “Node:Express JS” Application, then application maps those URLs to Hadlers as shown below

      http://localhost:3000/

      
      http://localhost:3000/    --> It maps to app.use('/', routes);
      app.use('/', routes);     --> It in turn maps to './routes/index.js'
      Then finally, it executes Functions defined in index.js
      Prepare Views and send that Response back to the Client
      

      Similarly, http://localhost:3000/users

      
      http://localhost:3000/users    --> It maps to app.use('/users', users);
      app.use('/users', users);     --> It in turn maps to './routes/users.js'
      Then finally, it executes Functions defined in users.js
      Prepare Views and send that Response back to the Client
      

Create New Express JS Routings

So far we have explored about Default Routings. To make it clear, we will create some new Routings.
We are going to provide the following CRUD operations Routings on USER domain object. We are not going to write much logic to perform any DB logic. We are just displaying some message.


/create    ----> createUser.js
/select    ----> selectUser.js
/delete    ----> deleteUser.js
/update    ----> updateUser.js

Please follow these steps to “Create New Express JS Routings”:

  • Please create new Routing Files under “${EXPRESSJS_PROJECT_ROOT_DIR}\routes” folder
  • createUser.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('User Created Successfully.');
    });
    
    module.exports = router;
    

    selectUser.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('Retrieved User Details Successfully.');
    });
    
    module.exports = router;
    

    deleteUser.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('User Deleted Successfully.');
    });
    
    module.exports = router;
    

    updateUser.js

    
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('User Updated Successfully.');
    });
    
    module.exports = router;
    
  • Create New View files
  • In real-time projects, we need to create some HTML Page or JADE templates or any Views for each Routings. However, for simplicity We are not going to write much logic.
    We are just using some useful message from Routing Function handler as shown in above step.

  • Load all newly created Routing files into Variables as shown below in app.js
  • 
    var createUser = require('./routes/createUser');
    var selectUser = require('./routes/selectUser');
    var deleteUser = require('./routes/deleteUser');
    var updateUser = require('./routes/updateUser');
    
  • Map Client Requested URLs to Routings in app.js
  • 
    app.use('/', routes);
    app.use('/users', users);
    app.use('/create', createUser);
    app.use('/select', selectUser);
    app.use('/delete', deleteUser);
    app.use('/update', updateUser);
    
  • Now its time to start our Express JS WebApplication to test our newly created Routings.
  • Open command prompt at our project ROOT Directory and execute the following command:

    
    npm start
    

    nodejs-express-execute

  • Access the URLs and observe the output console.
  • Access this url: http://localhost:3000/create

    expressjs_webapp_create_user_output

    Access this url: http://localhost:3000/select

    expressjs_webapp_select_user_output

    Similarly, we can test all our Express JS Routings.

That’s it about Express JS Routings. By using Enide Studio 2014 IDE Default “Node:Express JS Project”, We can update or add our requirements and can implement very big and real-time application.

Try to implement one real-time application.

Please drop a comment if you face any issues.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages