Reputation: 11239
I'm losing my understanding of parameters in a call back.
app.get('/', function(req, res) {
res.render('index');
});
// A route for the home page - will render a view
This is using the express library and is a basic home page route. I'm just confused on how does this actually get the req/res objects? Does the server itself invoke the function whenever it receives a req/res object on the '/' page ?
I understand what the function does, I just don't know how it actually receives its parameters.
Upvotes: 2
Views: 86
Reputation: 6787
Here is an intuitive way to look at it:
app.get()
is a function that takes 2 parameters, the first is your path taken as a string and the second param is a function. This function will be called back by app.get();
So let's say that you invoke app.get
like so:
app.get('/', function abc(req, res){..})
Then, the implementation of app.get
will be something along the lines of :
app.get = function(path, callBackFunction){
// do some stuff here to get the values of req and res
callBackFunction(req, res); // calling back the function passed to us with req and res
}
Upvotes: 1
Reputation: 150614
Yes, you get those parameters from the server. Whenever Express (i.e. Node.js) receives a request it runs your callback and provides those two parameters.
Think of it like a talk between two persons:
Please tell me and give me their phone number. is the callback. The phone number is the parameter to the callback.
So, the phone number in this case is the very same thing as your req
and res
objects. And I am acting like Node.js / Express in this example, you are the application that is run.
HTH.
Upvotes: 3