Intelligent HTTP Server in NodeJS: Part 2

Introduction

In my previous article, we began a HTTP module and tried to create a simple HTTP server for the request process. But, that was quite static (or, I say dumb). Whatever you request, it returns Hello World. And, I know Hello World is a cult but it doesn't mean you must pop up with this every time.

This time, we will improve that same code and make it more intelligent. so we can process the client's request.

Background

There is nothing new to say about the background details. We will use the same http module what we used in the previous article.

Without wasting time, let's move to the code part.

Pre-Requites

We need two dummy HTML pages that the client PC (in other words our browser) will ask for.

So, let's write two dummy HTML codes.

HTML codes

Save that as page.html (or, whatever you want).

Next,

page html

Save it as login.html

Note: Save these file where your Node code is. Or, keep it in a specific folder inside that root folder (where you are saving all your node's code).

Code

From the previous code, we will edit the createServer() method.

Code

So, if we look at this pretty code, then we will find an if-else clause that actually decides whether or not the server found the requested page.

Before proceeeding, be sure you have added the required (”fs”) module for this demonstration.

require

Since we tried to read the file from the local file system and then send its content as the HTTP response.

Note: There “./” points to the ROOT folder. If you have your HTML file in a specific directory then you can use their name instead of that. Say, “./PUBLIC/”.

login

Here, we have saved all our files in the root folder.

Rest are quiet explain try, where if your request is populated with an error then it will get inside an if-block and set the header value depending on that.

The response will be like “Sorry We can't find your page”.

And if it goes to the else block then it will respond to the request with HTML content.

So, let's try our output.

Output

After executing, you get the “Listening“ thing. Now, request from your browser.

When we request for the Page.html page:

request

Then, it shows the HTML content of page.html. At the same time, CMD is like:

content

And, if we request another page then:

request for another page

So, everything is working as expected.

As if, we requested the wrong HTML page, then it will show an error.

Which is like:

wrong

Here, we have requested error.html but that is an invalid name. So, it returns the error message we coded in the error-block.

Conclusion

This is much more intelligent than the previous one. Next, we will try to use the express framework that simplifies HTTP server problems and minimizes the code.

Regarding this, you are free to comment. Apart from this, Stay Raw and Keep Coding.


Similar Articles