Create Server in Node.js

In other programming languages it is complex task to create a server. During this process we have to face a lot of phases like install different types of software like WAMP and XAMP for PHP and apache for JAVA, But in Node.js after installing LTS our problem is solved. We have to use http module and adding few lines of codes.

HTTP module :

HTTP is a stateless data transfer protocol built upon a request/response model:clients make requests to servers, which then return a response.

Some Point regarding HTTP Module:

  • It is a built-in module.
  • It is allows Node.js to transfer data over Hyper Text Transfer Protocol.
  • It contains createServer method used for creating server in node.js.
Create Server in Node.js

After using Module http and adding few lines of code Server is created.
 Example :

  
   var http =require('http');

   var http = require('http');

    var server=http.createServer(function(req,res){

       res.writeHead(200,{'content-Type':'text/plain'});

       res.end('Hello Server');


});

server.listen('8080');

To Obtain Output we have to open command prompt and write following command.


localhost:8080

Output :

A Node server is typically created using the method of the http module: createServer

Proxy Server

by using a proxy, that one server can forwards requests to the right recipient.

Question : How to create Proxy Server in Node.js?

In Node.js it is very easy to create Proxy Sever after adding few lines of Codes Our Proxy Sever has been created as shown below.


var http = require('http');

var server=new http.Server();

server.on("request",function(request,socket){

       http.request({

           host:'www.google.com',
           method:'GET',
           path:"/",
           port:80
       },function(response){

           response.pipe(socket);

       }).end();

});
server.listen(8080);

To Obtain Output we have to open command prompt and write following command.


localhost:8080

Output :

 

Leave a Reply

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