I've just begun to work with NodeJS and I find myself puzzled on code such as
app.get('/home', function(req, res) {
// req and res are objects
})
I often see these kinds of function calls where the parameters in the anonymous function seem to come out of nowhere, yet contain various attributes and/or methods within?
You are passing a function to another function, this
function(req, res) {
}
is a function. Assuming you gave it a local variable name like b
in the called method, the function could then be invoked. As an example, -
app.get = function(a, b) { // <-- assign a function to app.get
b("one", "two"); // <-- and then req would be one, and res would be two.
}
This is actually found here:
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
As you can see, express()
is this
and it is being used as a parameter to createServer
.
You can find the documentation of createServer here:
The requestListener is a function which is automatically added to the 'request' event.
Then when you check the request
event here:
Event: 'request'
function (request, response) { }
Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). request is an instance of http.IncomingMessage and response is an instance of http.ServerResponse.
Technically this event gets emitted every time a new request from a browser is received.
And this code
app.get('/home', function(req, res) {
// req and res are objects
})
Is somewhat a listener for a request to this route (check expressjs source code).
So req
and res
are short-hand of request
and response
and are passed from the request
event.
Then express added some more methods/properties found here and here.
If you want to see the code for .get()
, see here.