Reputation: 11
In reference to Express app.post function shown below, I am trying to find documentation behind using one or optionally more than one callback function as parameters in the app.post function
I've researched the web, understood the concept behind spread operator, understand it means 2nd callback function or more but can't find any tutorial / reference on brackets [ ] as syntax for 'optionally' more than one
app.post(path, callback [, callback ...])
What I hope to understand or find a clear reference / tutorial on are:
Reference explaining the [ ] syntax
What is the sequence of execution to the callbacks passes, so assuming I called it as app.post(....., callback1, callback2); will callback1, callback2 be called in the same time? or will callback2 be called once callback1 returns?
Will the result returned from callback1 passed to callback2 as parameters (despite the parameters of callback2)?
Thanks for your help and time
Upvotes: 0
Views: 26
Reputation: 138267
1) Thats an optional parameter. You can either call it as if the parameters in the brackets would be there or as if the parameters in the brackets would not exist. So
method(a, [b, c])
// Could be either called as
method(a)
// or as
method(a, b, c)
2) callback2
gets executed when you call next
(the third argument) from callback1
, callback3
gets executed when you call next
from callback2
and so on.
3) No, all middlewares receive the request as their first, the reponse as their second and a next function as their third argument.
The usecase of these additional callbacks is to add middlewares to certain endpoints only:
function isAdmin(req, res, next) {
if(/*some checks*/) {
next(); // Go to next middleware
} else {
res.status(402).send("Not authenticated!");
}
}
app.post("/secret", isAdmin, function(req, res, next) {
//...
});
Upvotes: 1