Hey Guys, in this article we will learn how to build a small routing system with pure nodejs without any extra library or any package from npm, it is just pure node js from scratch, so let's get started.
first of all, you need the following things :
1- node js environment on your machine to install it go to this article
2- browser to test your code
3- text editor to code your program
4- your attention to focus well in this lesson
Now after installing the nodejs environment and opening the text editor, create a new file named app.js and let us start coding on it.
firstly we will require HTTP module the built-in module in nodejs to create the server and then require URL module also like the following code
const http = require("http"); const URL = require("url")
const port = process.env.PORT || 3000;
Ok now we are going to setup the server so we will use the createServer function of HTTP module and also use the listen to function to listen to the specified port so write the following:
// require dependencies const http = require("http"); const URL = require("url"); const port = process.env.PORT || 3000; // create the server const server = http.createServer(function (req, res) { // do some stuff here }): // make the server listen to the specified port server.listen(port)
after creating a server now let us imagine the structure of our program so we now need to make routes so to make the route we need specify things as:
1- method of request
2- the url of coming request
3- headers of coming request
4- query parameters of url if there are
5- the handler which will manage the routes
5- the handler which will manage the routes
so we will make variables with these requirements
// require dependencies const http = require("http"); const URL = require("url"); const port = process.env.PORT || 3000; // create the server const server = http.createServer(function (req, res) { // Do some stuff here // parse the requested url}) // make the server listen to the specified port server.listen(port);var url = URL.parse(req.url, true);/* Define some variables */var method = req.method.toLowerCase();var pathname = url.pathname;var query = url.query;var headers = req.headers;
var requestInfo = {method : method,url : url,headers : headers,query: query,pathname: pathname}/* End Defining variable */
Everything established inside createServer function. Now we need to create three objects
the first one will be fore getRoutes with the get method, the second one for post routes with post method and the last object will be for handler functions for each route. Inside get routes and post routes object will be objects for each route like this:
// require dependencies const http = require("http"); const URL = require("url"); const port = process.env.PORT || 3000; // create the server const server = http.createServer(function (req, res) { // Do some stuff here // parse the requested url}) // make the server listen to the specified port server.listen(port); // post routes object const postRoutes = { "/home": {var url = URL.parse(req.url, true);/* Define some variable */var method = req.method.toLowerCase();var pathname = url.pathname;var query = url.query;var headers = req.headers;
var requestInfo = {method : method,url : url,headers : headers,query: query,pathname: pathname}/* End Defining variable */} // Get routes object const getRoutes = { "/": { method: "get", handler: handlers.home }, "/user": { method: "get", handler: handlers.user } } // create handler objecthandler: handlers.postHomePage,method: "post"}};const handlers = {home: function (req, res, info) { // send the response message to home pageres.end("home page");},
user: function (req, res, info) { // send the response message to user pageres.end("user page");},postHomePage: function (req, res, info) {
// send the response message to post requestres.end("post home");}, // Define the error page if the requested url doesnt exist in routeserrorPage: function (req, res, info) { // send the response message to any error pageres.end("error page");}
In handler functions, we will return req which carries the request information from the user and we will return res which object has methods to send the response to user and the last parameter will be info which is object contains the request information that we defined inside create server function.
Then, we will return inside create server function to add some codes. Firstly, I am gonna make two if conditions to check the request method which GET or POST and based on that we will choose the specified router and the related handler of it.
// check if the method is good if (method === "get") { /* Define a variable named choseHnadler to detect the related handler with specified route*/var choseHandler = typeof getRoutes[pathname] !== "undefined" ? getRoutes[pathname].handler : handlers.errorPage //return the choseHandler function with req, res, and info if the method is GETchoseHandler(req, res, requestInfo);} else if (method === "post") {var choseHandler = typeof postRoutes[pathname] !== "undefined" ? postRoutes[pathname].handler : handlers.errorPage //return the choseHandler function with req, res, and info if the method is POSTchoseHandler(req, res, requestInfo);}
The final Code:
const http = require("http");const URL = require("url");const port = process.env.PORT || 3000;const server = http.createServer(function (req, res) {// parse the requested urlvar url = URL.parse(req.url, true);/* Define some variable */var method = req.method.toLowerCase();var pathname = url.pathname;var query = url.query;var headers = req.headers;/* End Defining variable */var requestInfo = {method : method,url : url,headers : headers,query: query,pathname: pathname}// check if the method is goodif (method === "get") { /* Define a variable named choseHnadler to detect the related handler with specified route*/var choseHandler = typeof getRoutes[pathname] !== "undefined" ? getRoutes[pathname].handler : handlers.errorPage //return the choseHandler function with req, res, and info if the method is GETchoseHandler(req, res, requestInfo);} else if (method === "post") {var choseHandler = typeof postRoutes[pathname] !== "undefined" ? postRoutes[pathname].handler : handlers.errorPage //return the choseHandler function with req, res, and info if the method is POSTchoseHandler(req, res, requestInfo);}});server.listen(port);const handlers = {home: function (req, res, info) {
// send the response message to home pageres.end("home page");},
user: function (req, res, info) { // send the response message to user pageres.end("user page");},postHomePage: function (req, res, info) {
// send the response message to post requestres.end("post home");},errorPage: function (req, res, info) {
// send the response message to any error pageres.end("error page");}};const getRoutes = {"/": {handler: handlers.home,method: "get"},
"/user": {method: "get",handler: handlers.user}};const postRoutes = {"/home": {handler: handlers.postHomePage,method: "post"},}
Hopefully, you enjoyed this explanation If you have any issue or problem while coding it, write a comment below with your issue, good luck.
Thanks for the head start! I decided to sit down and see how hard it would be to roll my own lambda service. This is a good beginning.
ReplyDeletefollow us to learn more
ReplyDeleteThis post is more informative. Thanks for sharing this valuable information.
ReplyDeleteLeadership Programs
Management And Leadership Training