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
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.
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).
var email = req.body.email;
var password = req.body.password;
Perform the login and send a response.
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.
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.
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.