Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS http module: what is requestListener?

I'm new to JS and more specifically Node. Even after reading the api docs, I'm confused about what 'requestListener' is in the following method.

http.createServer([requestListener]);

Searching google revealed that 'requestListener' is a(n) (anonymous) function with the following signature:

function (request, response) { };

I suppose I'm reading the docs incorrectly, hopefully someone can point me in the right direction.

like image 384
ay18 Avatar asked Jan 02 '15 22:01

ay18


1 Answers

The docs say that the method call takes a function which will be called when a new request is received by your application. This function, as you correctly stated in your question, takes two arguments - a request and response objects.

You should inspect the contents of these objects to learn what information is available to you. Also, take a look at the API docs for request and response.

The function is optional; you could also attach the request handler in the following way:

var server = http.createServer()

server.on('request', function (req, res) {
  // Process the request here
})

In practice, this function is called when someone opens up your website in their browser (i.e. issues a GET http request). The purpose of that function is to provide a HTTP response body back to the client, i.e. render a web page or perform any business logic as necessary.

like image 137
Robert Rossmann Avatar answered Sep 21 '22 21:09

Robert Rossmann