Setting up an HTTP Server and handling Requests and Responses using Node JS

Setting up an HTTP Server and handling Requests and Responses using Node JS

When interacting on the web, most times we find ourselves requesting some form of information embedded in a web page. That webpage is stored in a web server and we get access to it using by making HTTP request using some form of endpoint which then send back a response in the form of an HTML page or some JSON data.

In my last post, I explained how we can create a mock server and make CRUD operations to various endpoints using JSON Server, you can read all about it here.

In this post, we will be going on a long journey to build a web server from scratch using Node JS. If you are new to Node JS, you can get started by reading my previous article on Node JS here.

To create a server with Node JS, ensure you have a Node Installed on your PC, then, in your code editor, preferably, VS Code, create a new file called "server.js".

At the topmost of your server.js file, write the code below;

const http = require("http");

Let's take a moment to discuss the line of code we have above. As you may see, we are creating an instance of the "HTTP module" and storing it in a constant called "HTTP". HTTP itself stands for Hypertext Transfer Protocol, which is the set of rules for transferring files -- such as text, images, sound, video and other multimedia files -- over the web. In our case, we want to be able to send and receive a web page that may contain text, images, etc over the internet, which is why we are requiring it in our document.

Next for us is to define the location our web server will be hosted. This involves creating two variables called localhost and port in our server.js file. See the code below;

const host = 'localhost';
const port = 3000;

In the code above, localhost refers to the location or internal IP address of our computer which typically points to 127.0.0.1. While the port refers to the entry point to that address. The port number can be 3000, 4000, 5000, 8000, etc.

From our little configuration above, we can now access our server using the endpoint localhost:3000.

Next, we have to create a function called "Request Listener." This function handles all incoming HTTP requests to the server. It holds two parameters, called request and response. The request parameter contains all information concerning the request, like the request method, request URL, request body, etc while the response parameter contains the information to be sent. See the code below on how we can go about this;

const requestListener = function(request, response) {
    response.writeHead(200);
    response.end("Yay! I created my first server!");
}

In the code above, we are making it so that when we make a GET request to the endpoint we created localhost:3000, we can send a response status code of 200 which entails the request is a success and then display the text "Yay! I created my first server!" using "response.end" on the page. We have not yet concluded the functionality for this to work fully though, but the code above ultimately creates a response we will send when such a request is made to the endpoint.

Next, we will create a server by calling the "createServer" method on the HTTP instance we created at the beginning of our file. Then, we pass in the requestListener function as an argument. See the code below;

const server = http.createServer(requestListener);

From the code above, our requestListener function is now attached to the server we created. Next, we have to listen to requests made to the endpoint we created. We can do this by calling the listen method on the server.

See the code below;

server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});
//Expected out put in the console is "Server is running http://localhost:3000"

In the code above, we are just listening to requests made to the endpoint we earlier created, we are also using the port and host variables we earlier created.

With these simple steps, we have created our server and we are now listening to requests in real-time.

As an overview, when a request is made to the endpoint localhost:3000, our server listens for it and calls the requestListener function, which then sends a response status code of 200 indicating the request is a success and then sends the text "Yay! I created my first server!" to be displayed on the browser page. This is a basic illustration of how HTTP requests are processed by a server and the response sent to the user which we then see on our browser.

You might have noticed that in our requestListener function, we are sending a single text which says "Yay! I created my first server!" as a response to our GET request called on the endpoint localhost:3000. In the real world, we would be expecting an HTML page like the homepage of the website or a JSON object to be sent when a request sends to its respective endpoint. So let's demo that in a single code block.

RETURNING A JSON OBJECT AS A RESPONSE

const http = require("http");

const host = 'localhost';
const port = 3000;

const requestListener = function (request, response) {
    response.setHeader("Content-Type", "application/json");
    response.writeHead(200);
    response.end(`{"message": "This is a JSON response"}`);
};

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

In the code above which is a summary of what we have been doing so far, we are sending JSON Object as a response to a request made to our endpoint localhost:3000. JSON simply stands for Javascript Object Notation which allows us to store information in key and value pairs. The major difference the code above has from our previous one is in the requestListener function. In the requestListener function, we are sending a setHeader response which specifies the type of content we are sending as a response, we set our response status to 200 which indicates its a success using response.writeHead and finally, we send our JSON Object using response.end.

You can read more about JSON Object in my previous article here.

RETURNING AN HTML AS A RESPONSE

The majority of the time, our response to a request being made to a server will be in the form of an HTML page. Here, I'll be making an overview of how such a response will look in its most basic form.

const http = require("http");

const host = 'localhost';
const port = 3000;

const requestListener = function (request, response) {
      res.setHeader("Content-Type", "text/html");
      res.writeHead(200);
      res.end(`<html>
                    <body>
                        <h1>Hello World</h1>
                      </body>
                    </html>`);
   };

const server = http.createServer(requestListener);
server.listen(port, host, () => {
    console.log(`Server is running on http://${host}:${port}`);
});

In the code block above, the only difference again is the requestListener function where we set our content type set to text/html using res.setHeader and our response comes in the form of an HTML document. Ideally, we would want to create a page folder that contains all our HTML pages and using the FS Module which I wrote about in a previous post, we redirect users to a particular page depending on the endpoint a get request is made to. However, this way will suffice for now.

Phew! We've come to an end. Hopefully, you now have a picture of how to set up a server using Node JS and how to handle requests and responses.

Please, share the link and subscribe to my page. I will be building on this topic soon.