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:

})
// 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:

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*/

Connect With us

Over 600,000+ Readers Get fresh content from FastBlog

how to

About Me

I am a programmer and technical writer i have 3 years experience in programming and technical writing, i hope helpe people to know more iformation about programming and technology in global. Learn More →