HTTP Request In Node.js


Here we are request a server with defined host and port to get a response from server. This is basically created by callback function (non-blocking). Also here I mentioned some modules. The modules can be explained in coming posts.

// Importing the HTTP module from node_module
var http = require("http");

// Print some text to check the start
console.log("Starting");

// Host and Port Address
var host = "127.1.1.1";
var port = 1337;

/* Creating a callback function which fired every single request that contain the url from client request and response is similar as request. here we are importing the createServer class from http module(http.createServer)*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
response.writeHead(200,{"Content-type":"text/plain"});
response.end("Hello");
}
);

//Server Listening
server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After completing this code ,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1003
4) you will get the “Hello” in browser.

1 comment:


  1. Thanks Admin, I just begin my career in sever side web application development for that I complete the Node JS training but I wish to explore more in that, truly your blog provide some useful information and I would like to share your blog in my friends circle so keep sharing.
    Regards,
    Node JS training in chennai

    ReplyDelete