Basic HTTP Server Using NodeJS From Scratch

                                                                No. of Pic = 1
                                                         No. of Links = 1+1=2
                                                       Credits: >Sachin Sarawgi
In this blog, we will see how to create an HTTP Server to handle GET, POST, PUT, DELETE request method type from scratch.
We need to have Node.js installed in our machine for the code to work. We will be using ‘http’ module provided out of the box to get the request and response object. We will not use any other custom library.

Steps For Creating A HTTP Server

  1. Create Server using http module and add a listener
  2. Do the necessary entry check for the request
  3. Extract request method type
  4. Writing handler for Http GET request
  5. Writing handler for Http POST request
  6. Writing handler for Http PUT request
  7. Writing handler for Http DELETE request

1. Create Server using the http module and add a listener


First of all, we need to create a server that will listen to some particular port. So that if any request comes to that port the listener will be called.
We can do this using the http module.
createServer method accepts the listener as an argument. listen method takes the port number where it will keep listening.
Let’s see what empty requestListener method looks like.

2. Do the necessary entry check for the request

Suppose we want our server to support REST API, and we want to have the following checks on request object:
  • Content-Type is application/json
  • Accept is application/json.


We will be using the req object to get headers details and check the required values.
Let’s understand what’s going on.
  • First, we declare constant for content-type and accept header which our server will support
  • Next entryCheck is the method where we will check if the request headers have the required and matching details.
  • If either Content-type or Accept is not matching we will throw an error.
Now let’s see how we will call this method from type listener.
  • writeHead method takes the HTTP Status code, it could be any valid status code. It has some optional parameters too, the second is a status message and the third is headers.
    • end method takes the response body which will be shown to the user. After this method, the response is sent back and the whole request-response process is done.
    Note: We can add multiple entry checks depending on our condition like a cookie, hostname/IP address, a particular header etc.

    3. Extract request method type

    We need to know the HTTP method type to handle each one of them separately.


method property of request object gives us the Http method type like GET, POST, PUT, DELETE.
Next, we can use a switch to handle different Http requests type differently

4. Writing handler for Http GET request

Http GET requests are generally for finding an existing object by sending unique details
We can simply return a generic response in every kind of Http method type.
But instead of just returning simple response let’s create some object and apply operations on it.
Let us consider an employee object with the following fields:
We will have an object containing an array of above employee objects.
Consider GET request where we will ask for particular employee detail by providing the _id value.
Now we will need one method which will search for the request _id in the array of objects. We will write one method to search employee based on _id:
Let’s rewrite the GET Http handler code
We have written a separate method
  • First, we found the requested _id
  • We pass that _id to findEmployee method to get the employee object
  • Next, we check if an employee object is found or not if not we throw an error. If everything goes fine we return the employee object in the response body.

  • 5. Writing handler for Http POST request

    Http POST requests are generally for inserting the new objects. In our case, we will add the received employee object to the array. Let’s write code for that method
    Next, we need to handle the POST request and parse the request body to get the employee object we need to insert:


Let’s understand what we did here.
  • We defined a method getRequestBodyAndGenerateResponse(req, res, postMethodHandler).
  • This method reads the data from the req object by listening for the ‘data’ event and append it to one variable body.
  • Once the ‘end’ event is triggered means the request body read completely, it parses the string into JSON and calls the callback function passed to it.
  • This callback function is the one that prepares the response object.
  • In the callback function first, we add the employee to employee array.
  • Then prepare a response and sent it to the user.

6. Writing handler for Http PUT request

Http PUT requests are generally for updating the old objects. In our case, we will update the received employee object if present inside the array. Let’s write code for that method

Next, we need to handle PUT request and parse the request body to get the employee object we need to update:
Let’s understand what we did here.
  • We defined a method getRequestBodyAndGenerateResponse(req, res, putMethodHandler).
  • This method reads the data from the req object by listening for the ‘data’ event and append it to one variable body.
  • Once the ‘end’ event is triggered means the request body read completely, it parses the string into JSON and calls the callback function passed to it.
  • This callback function is the one that prepares the response object.
  • In the callback function first, we update the received employee object inside the employee array.
  • Then prepare a response and sent it to the user.

7. Writing handler for Http DELETE request

Http DELETE requests are generally for deleting an existing object. In our case, we will delete the received employee object _id from the array. Let’s write code for that method
Next, we need to handle the DELETE request, get _id of the employee, and delete that object from the array.
Let’s understand what we did here.
  • First, we found the requested _id
  • We pass that _id to deleteEmployee method to delete the employee object
  • If everything goes fine we delete the employee object.
  • Then prepare a response and sent it to the user.
You can find the above code here. I tried to convert it into a modular format by separating data, methods, and using a module export-import feature of JS.

 

Comments

Popular posts from this blog

What is the BEST way to Practice "Cracking the CODING Interview Problems?

Which laptop Should you Buy for Intense Programming(i.e.to develop advanced projects)