Got page not found when use extra arguments in express router

Viewed 23

So i have a 404 handler and a router file:

404 handler:

app.all("*", (req, res, next) => {
    res.status(404).json({
      "status": "failed",
      "message": "woops, page not found..."
    })
})

Router:

orderRouter.route('/')
        .post((req, res, next, optionalData) => {
            res.status(200).json({
                "status": "ok"
            })
        })

module.exports = orderRouter

As we can see, i add extra arguments in middleware, that is "optionalData".

When i access the route / method POST, i got 404 result.

But when i define that optionalData = undefined, it works. I got results "status": "ok".

(req, res, next, optionalData = undefined)

But why? what happen here..

1 Answers

Express regular request handlers are expected to have no more than 3 arguments as you can verify here.

And looking up Function.length:

length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number excludes the rest parameter and only includes parameters before the first one with a default value.

It becomes clear why the second function works and the first one doesn't:

(function(a, b, c, d = undefined) {}).length === 3
(function(a, b, c, d) {}).length === 4
Related