Routing System in Pure nodejs - torok-technology torok-technology: Routing System in Pure nodejs

recent

all you want in technology

Post Top Ad

Post Top Ad

Wednesday, 30 May 2018

Routing System in Pure nodejs




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")

after that, we will define the port to make the program listen to it and for that usually, we define the port 3000 but if you will deploy the project you will need to make the port defined automatically, so for this purpose we will define port 3000 or process.env.PORT which detects the free port on the server automatically so make the following:
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
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
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 */
}) // make the server listen to the specified port server.listen(port);


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
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 */
}) // make the server listen to the specified port server.listen(port); // post routes object const postRoutes = { "/home": {
handler: handlers.postHomePage,
method: "post"
}
} // Get routes object const getRoutes = { "/": { method: "get", handler: handlers.home }, "/user": { method: "get", handler: handlers.user } } // create handler object
const handlers = {
home: function (req, res, info) { // send the response message to home page
res.end("home page");
},
user: function (req, res, info) { // send the response message to user page
res.end("user page");
},
postHomePage: function (req, res, info) {
// send the response message to post request
res.end("post home");
}, // Define the error page if the requested url doesnt exist in routes
errorPage: function (req, res, info) { // send the response message to any error page
res.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 GET
choseHandler(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 POST
choseHandler(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 url
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;
/* End Defining variable */
var requestInfo = {
method : method,
url : url,
headers : headers,
query: query,
pathname: pathname
}
// 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 GET
choseHandler(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 POST
choseHandler(req, res, requestInfo);
}
});
server.listen(port);
const handlers = {
home: function (req, res, info) {
// send the response message to home page
res.end("home page");
},
user: function (req, res, info) { // send the response message to user page
res.end("user page");
},
postHomePage: function (req, res, info) {
// send the response message to post request
res.end("post home");
},
errorPage: function (req, res, info) {
// send the response message to any error page
res.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.

No comments:

Post a Comment

Post Top Ad