0

Ok look at this code..

var http = require('http');

var handleRequest = function (request, response){
    response.writeHead(200,{"context-type":"text/plain"});
    response.end('Welcome to the node club! :)');

}
//the createServer method... creates a server WOW!
http.createServer(handleRequest).listen(8888);

console.log('The servers are running and the bacon is stopping');

It seems simple enough, the handleRequest function will create a writeHead function when the node will allow me to respond ...right? And if that is the case, I will be able to write out "Welcome to the node club" in the end method. The thing I don't understand about node is the request variable or object or whatever. In the function am I requesting the node? Or is the node requesting me to run a function? I'm not using the request variable in the function so would it still run if I left it out?

black_yurizan
  • 407
  • 2
  • 7
  • 19
  • its the incoming request... its an object itself that you or someone else sends to the server... – omarjmh May 17 '16 at 01:41

1 Answers1

2

The argument to http.createServer is a function to be called on each request. The function is documented as

function (request, response) { } request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.

What you do in this function is up to you; it can be anything.

However, virtually all web applications end up writing an answer to the client, and that's done via the response object. Also, since an application that serves just one page is quite limited, most applications also want to get information from the HTTP request, including the path requested (something like '/questions/37265770/so-about-requesting-in-node-js', in request.path), HTTP POST parameters and the like.

Your function gets called with two arguments, the first of which is the request object, the second the response object. There is no magic involved - you seem to call magic "node", but that's just the name of the project.

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469