Node.js HTTP Package – Creating HTTP Server

Filed Under: Node.js

An HTTP server caters to client requests and sends appropriate response. For example, JournalDev is also running on HTTP server. If you have landed here directly, I would suggest you to go through earlier posts about NodeJS IO Package and NodeJS Modules because we will use that knowledge here to create a simple HTTP server Node.js application.

In this post, we are going to discuss about Node JS Platform “HTTP” module to develop HTTP server.

  • Introduction to Node JS HTTP Module
  • Node JS Simple HTTP Server
  • How Node JS HTTP Server handles Client Requests
  • Node JS HTTP Server Routings

Introduction to Node JS HTTP Module

Implementing an HTTP server is a tough task in Java or any other language frameworks, that’s why we have so many HTTP servers for different platforms such as Apache, Tomcat etc. However, we can develop simple HTTP server by using Node JS Platform very easily. We don’t need to write too much code to develop, up and running a basic HTTP Server.

Like some Node modules for example “npm”, “fs” etc., Node JS “http” module is also part of basic Node JS Platform. We don’t need to do anything to setup Node JS HTTP module.

We just need to import “http” module and starting writing some code to develop HTTP server.

To import a “http” module:


var http = require("http");

This require() call imports Node JS HTTP module into cache. Once it’s done, then we can use NODE JS HTTP API to develop HTTP Server.

Node JS Simple HTTP Server

Here we will learn how to create a simple HTTP server step by step.

  • Create a simple Node JS Project, refer Node JS Basic Examples With Node REPL (CLI) and Node IDE for detailed steps.
    node.js-http-server-project
  • Create package.json file with below contents.

    package.json

    
    {
      "name": "http-server",
      "version": "1.0.0",
      "description": "Simple HTTP Sever",
      "main": "http-server",
      "author": "JournalDEV",
      "engines":{
      	"node":"*"
      	}
    }
    
  • Create a JavaScript file with the following content;

    http-server.js

    
    /**
     * JournalDEV  
     * Simple HTTP Server Example
     */
    var http = require("http");
    var httpserver = http.createServer();
    httpserver.listen(8001);
    

    With just few lines of above code, we are able to create a simple HTTP server. Below is the explanation of different parts of the code.

    • First line, require() call loads http module into cache to use Node JS HTTP API.
    • Second line, using HTTP API we are create a Server.
    • Third line, HTTP Server listen at port number: 8001

    Below image shows the project structure for now.

    node.js-http-server-eclipse-project

  • Open command prompt at ${ECLIPSE_WORKSPACE}/http-server project and run “node http-server.js” command.
    node.js-http-server

    If we observe here, command is waiting for client requests that mean our simple Node JS HTTP Server is up and running successfully.

However, it cannot handle any requests with this simple HTTP Server. To handle or provide services to Client requests, we need to add some Routings. Please refer next section to extend this Basic HTTP Server program to handle client requests.

How Node JS HTTP Server handle Client Requests

Now we are going to add some code to receive and handle HTTP Client request.

Open http-server.js file in Eclipse IDE and add a JavaScript function to represent request and response objects.


/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var httpserver = http.createServer(
			function(request,response){
				
			}
		);
httpserver.listen(8001);

Here anonymous Function takes request and response as parameters. When an HTTP Client sends a request at port number 8001, this anonymous function will receive that request.

Let’s add some code to send response to the client requests.

http-server.js


/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var httpserver = http.createServer(
		function(request,response){
			console.log("Received a Client Request");
			response.write("Hi, Dear JournalDEV User.")
		}
	);
httpserver.listen(8001);

Here when HTTP server receives a Client request, it prints a log message at server console and send a response message to the Client.
Just start the server again in the command prompt, if the earlier server is running then you need to close and start it again.

Now open a browser and go to URL http://localhost:8001/ and you will get below response.

node.js-http-server-response

At the same time, you will observe server logs in the command prompt as shown below.

node.js-http-server-logs

Node JS HTTP Server Routings

So far we have developed a simple Node JS HTTP Server that just receives HTTP client request and send some response to the server. That means it handles only one kind of request: “/” when client hits this url: “http://localhost:8001”

It’s not enough to run some real-time applications with this basic HTTP Server. To handle different kinds of Client Requests, we should add “Routings” to our HTTP Server.

Create a new JavaScript file “http-server-simple-routing.js” with following content.

http-server-simple-routing.js


/**
 * JournalDEV  
 * Simple HTTP Server Example
 */
var http = require("http");
var url = require('url');

var httpserver = http.createServer(
function(request,response){
	var clientRequestPath = url.parse(request.url).pathname;
switch(clientRequestPath){
	     case '/':
		console.log("Received a Client Request: Switch Case");
		response.write("Hi, Dear JournalDEV User: Switch Case.");
	       break;
	default:
	       console.log("Received a Client Request: Switch Default");
		response.write("Hi, Dear JournalDEV User:S witch Default.");
		break;
}
	response.end();
  }
);
httpserver.listen(8001);

Here we are using another Node JS Platform Default module: “url”. That means we don’t need to install it manually, it will come with base Node JS Platform installation.

Anonymous function with two parameters: request and response. request object contains a property: url, which contains client requested url.

Then we are calling url.parse(request.url).pathname to get client request url. Suppose if Client sends a request by using http://localhost:8001/ url, then here url.parse(request.url).pathname returns “/”.

We are saving the output of url.parse(request.url).pathname value into a local variable: clientRequestPath. We are using switch() block with one case and default blocks. If user sends request using “/”, then server executes switch:case block and send respective response to the client.

If user sends different request, then then server executes switch:default block and send respective response to the client.

We are closing the Response object using response.end() call.

Open the Command Prompt/Terminal and start the node http server “http-server-simple-routing.js” and send two different requests from client browser and observe the response.

Case 1: Client sends “/” request using http://localhost:8001/ url and you will see below response in browser.

node.js-http-server-routing

Case 2: Client sends “/index.htm” request using http://localhost:8001/index.htm url and gets below response.

node.js-http-server-routing-1

Below image shows the server logs in these cases.

node.js-http-server-routing-logs

Here we have gone through some Routings to provide services to Client requests. We will see some more complex routings in next post “Node JS: Socket IO Module”.

To create a simple HTTP Server with simple Routings, we have written some amount of code using Node JS HTTP package. If we use Node JS Express module, then we can create similar kind of Web Servers very easily. We will see those examples in “Node JS: Express Module” in coming posts.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages