Here we will see an example of how we can make our http server work by writing a re-factored code or by using an anonymous function.First let us see an example of re-factored code.
Let us import the http module
var http = require("http"); // variable name can be any thing whatever we want.
function clientRequest(req, resp) {
resp.writeHead(200, {"Content-Type": "text/plain"});
resp.write("creating an http server in a re-factored way");
resp.end();
}
http.createServer(onRequest).listen(8081);
Now we will see how we can make an HTTP server work by passing an anonymous function in the createServer() which is one of the function of the “http” instance and which returns an object that uses it's method listen(port number) to take the client request.
Let us first import http module
var http = require("http"); // variable name can be any thing whatever we want.
http.createServer(function(req, resp) { // using anonymous function
resp.writeHead(200, {"Content-Type": "text/plain"});
resp.write("creating an http server by passing anonymous function.. ");
resp.end();
}).listen(8081);
0 Comment(s)