Express Complete Tutorial : Part 3

Routing is a mechanism to handle the request coming from client, finding out what is a request, processing the request and sending a response to client back.

In Express you can easily handle the router of your app. Depending upon the HTTP request you can identify and process the request.

Express handle the router by using instance of express. for.eg

var express=require('express');
var app=express();
/*
    You can further use app to handle routes.
*/

Below i am going to cover some router case. Each case is helpful for your web application.

Case 1 : On hit of home page URL deliver the index.ejs file.
Router code:

app.get(/’.function(req,res){
    res.render(‘index’);
});

Here when you specify index, Express will automatically find and render it to client. It basically look over the setting we did in part 1 of this series.

Case 2 : Handle Login request (POST).
Router code:

app.post(/login’.function(req,res){
    var email   =   req.body.email;
    var password  = req.body.password;
    /*
    Perform the login and send a response.
       */

        res.json({"done":"yes"});
        //OR
        res.render('account');
});

I use body-parser middleware to handle POST data which is really very easy. To know how to configure this in Express web project, please visit part 1 of this series.

Case 3 : Handle GET Request and Data.
Suppose request is like this.

http://www.example.com/profile?id=100022

You need to extract the ID in order to load the profile of user.
Router code:

app.get('/profile',function(req,res){
       var profile_id=req.query.id;
       res.render('profile',{id:profile_id});
});

This will load the profile.ejs and pass the profile_id to the ejs script. You can use <%%> block to access the parameters of ejs script. To learn more about ejs scripting you can visit part 2 of this series.

Case 4 : Send JSON response.

There are many cases when you need to response the client in JSON format. Express made it easy for you.
Router code:

app.get('/logout',function(req,res){
       res.json({"logout":"yes"});
});

In next post i will discuss with you about Session handling in Express. Stay tuned.

Shahid
Shahid

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

Articles: 126