I typically see Express routes as follows and have questions about multiple parameters passed to app.get()
.
I understand typical usage with callback function function(req, res)
however am confused about the cases where the callback has multiple parameters or app.get()
receives multiple parameters.
Standard and documented:
app.get('/', function(req, res){
});
However, I also see other usage with multiple parameters:
app.get('/user/:id/edit', a, b, function(req, res){
});
I’m assuming function a(req, res)
, function b(req, res)
, so above is just a list of callbacks. Is the response just appended left to right?
app.get('/example/b', (req, res, next) => {
})
In this case the callback have an extra argument next
. Does the Javascript compiler always provide next()
and it’s simply dropped in the above handlers where they have no third argument?
Thanks
2
Answers
Also documented:
(with the
[]
indicating optional arguments and the...
indicating repeating ones).The functions are called, in sequence, left to right. Each will have the usual arguments passed to them.
The arguments are passed by a function that is part of Express, not the compiler per se.
Any function that doesn’t register a parameter for an argument will drop it (mostly; see the arguments object):
What you’re confusing is an Express route and middleware.
Middleware functions have access to the request and response objects and also passes in a third value / function,
next()
, which, when called, allows the chain to progress either to the next middleware function or into the main functionality of your route.Middleware should be used to perform logic / additional measures to prequalify or change a request being made. Common use cases for middleware as things like:
You can have any number of middleware functions being used by your route, which is why in example 2 that you’ve provided, both a & b are middleware functions.
Middleware functions are attached to the router by using
app.use()
at a global level orroute.use()
at route level.