Using Node.js Http Module

As I mentioned earlier in Node.js Modules tutorial,Node.js has built in modules and Http module is one of them. This module is used to transfer data over hyper text transfer protocol(http).

To use http module we need to include it in our script  using require function.

var http=require(‘http’);

Creating a webserver using Node.js Http Module.

We can create a webserver that listens to requests using a certain port number using Http createServer function.

Adding Http Headers

You will be required to define the content type that the server will deliver.For example of the content from the server is supposed to be html,you have to had Content-type as html.

res.writeHead()  method has two arguments. One is Code 200 which means all is okay and  second is object with response headers.

Reading Query String

The function that is passed to http.createServer() function  has two arguments  i.e is req and res.

Req argument represent the request from the client that comes as a object (http.IncomingMessage  obj) which has “url” property that  comes after the domain. Eg www.techoverload.net/node.js url here is /node.js

Execute below code.



Node.js Http Module

Built-In methods to Split query string

There are inbuilt methods that can be used to split the query string so that it is easily readable.Example is url module

Copy below code

Save as > query_string_example.js

Open node.js command prompt 

Node.js Http Module

Open your browser and type >localhost:8080/?year=2017&month=July







About the Author: Eric K

Kenyan Developer and Blogger with Interests in Java,Javascript,Node.js, Wordpress, Android, PHP and Making Money Online. Solving world problems through programming is my passion. Hire me: Email : kawi3462@gmail.com