Simple Node.js HTTP Server

In this lesson, you will be able to understand how you can use node.js to develop your simple HTTP server

Node.js comes with http/https modules which can be used to develop the HTTP server

So to create Node.js HTTP server you require HTTP module and then you create the server from that module and finally you bind the server to the port to listen

Next you can start the server with following command in terminal

Now  you can visit localhost:3000 from your browser

Important

In this code you can see the callback function inside the http.createServer. This callback function will be called every time when you make a request. Inside the callback function you have request and response

You can write the callback function separately as shown in the below. This method is very easy for you to manage the code

So, How you are going to handle routing here?

We will see how we are going to route following URL
http://localhost:8000
http://localhost:8000/products
http://localhost:8000/product/add

You can see the switch statement inside the httpCallBack function

Form submission in Node.js Server
Now lets look at how we can submit form to this Node.js HTTP server. First create the form http://localhost:3000/product/add

When you hit the submit button server should identify the request is coming with POST data. We can use the following code for it. We have if(request.method === 'POST') to identify it. Then we should read the POST data. We can use following code to read data

This is the completed code of the form submission

Note

This HTTP module has very low level features so it is very difficult to build complex web application using this module. You have to develop most of the functions by scratch, which needed for complex application

Building from scratch is time consuming task and it needs lots of testing too

Luckily you have good Node.js frameworks for building complex web applications. They are very robust and rich with the features
There are lot of frameworks but these are the most popular ones:
express
hapi
koa
restify

Leave a Reply

Your email address will not be published. Required fields are marked *