skip to Main Content

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


  1. However, I also see other usage with multiple parameters:

    Also documented:

    app.get(path, callback [, callback ...])

    (with the [] indicating optional arguments and the ... indicating repeating ones).

    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?

    The functions are called, in sequence, left to right. Each will have the usual arguments passed to them.

    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?

    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):

    function foo(a, b, c) {
      console.log(a + b);
    }
    
    foo(1, 2, 4, 8);
    Login or Signup to reply.
  2. 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:

    • Validating access tokens
    • Validating route access
    • Parsing request body
    • Configuring CORS rules
    • Etc.

    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 or route.use() at route level.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search