Friday, October 9, 2015

Build your first HTTP Server using NODE.JS

In this blog, I will be talking about how you can create a HTTP server using Node.js. Later in the blog I will talk about creating "Hello World" app using Express.js

I will start by creating an empty file named Server.js and write the following code in it.


Detailed Explanation of the Above Code


Loading the HTTP module

Node.js has built-in modules to create HTTP server. The first line uses the require function to load a built-in module called http.




Creating the server

We need to create a HTTP Server object to create a server. So, the variable app takes a function that will listen for requests.
The writeHead() is called to write the header of the response. In our case, Http Status is 200 and Content-Type is text/plain.
The end() method sends the response to the client.



Starting the Server

To start a s server we call listen method on the server object.



Run the Server

In the terminal, write the following command:

node FILE-NAME.js

Create a simple application using Express.js


- Express.js is a node.js web application framework.

- Before you start using Express, don't forget to install it.

npm install Express




- We require express and node's http module.
- The express() function is a top level function exported by the express module.
- In the above example we are calling HTTP Get method.

You can use a browser to do a GET request just by entering http://localhost:9090 or you can use Advanced REST client.

After successful execution of the above program, output would look like: 


Now, you have a HTTP server up and running.

1 comment: