Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Make an HTTP server work by function passing as an anonymous function in Node

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 981
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: