Andrei Rosu Andrei Rosu - 23 days ago 7
Javascript Question

What's the purpose of multiple root handlers?

As stated, multiple callback functions can be provided and behave like middleware to handle a request. They can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.

For example:

app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})


What's the purpose of this? Can't we simply use:

app.get('/example/b', function (req, res) {
console.log('the response will be sent by the next function ...')
res.send('Hello from B!')
})

Answer Source

The multiple functions would more likely be used when you already have a previously defined function that you probably intend to use in multiple places. For example:

app.get("/somePath", checkAuth, function(req, res) {
    // you know it's already authenticated here
});

app.get("/someOtherPath", checkAuth, function(req, res) {
    // you know it's already authenticated here
});

function checkAuth(req, res, next) {
    if (some logic here) {
        // allow handler chain to continue
        next();
    } else {
        // auth error
        res.status(401).end();
    }
}

Of course, you could also use middleware for checking authentication, but the above example allows you to target just a few specific routes with some middleware that you may use in multiple places.


As you have already observed, if you don't intend to use the function anywhere else, then you may as well just put the logic into your one handler.