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 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:
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:
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.
You need to extract the ID in order to load the profile of user.
Router code:
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:
res.json({"logout":"yes"});
});
In next post i will discuss with you about Session handling in Express. Stay tuned.
This post is part of Express Complete tutorial Series.
Part 1: Configuration of Express.
Part 2: Templating Using EJS.
Part 3: Handling routes.
Part 4: Handling Session.
Part 5: Finalising App.