Tuesday 6 June 2017

How do I chain Express Router middleware

I've created an Express application and I'm using the following:

app.use('/', adminRouter)
app.use(errorMiddleware)

The admin router is defined in another file, like this:

const router = require('express').Router()
router.post('/admin/upload/', myController)

Inside myController, I'm throwing an error:

return throwSomeError().then(() => {
   return res.status(200).send('OK)
}).catch(next)

which is caught and forwarded to the errorMiddleware via the next function.

Everything's OK so far. If I add another middleware to the router middleware chain:

router.post('/admin/upload/', (req, res, next) => { next() }, myController)

something weird is happening. The new middleware does invoke myController, which in turn throws the error, which is caught, but this time the .catch(next) does not forward the request to the errorMiddleware. The request hangs, and I get a 404 response.

Why adding a middleware inside the router.post method breaks the chain and prevents the errorMiddleware from being called?

Is it OK if I use arrow functions? I've tried replacing them with the function statement, but still the same.

Also, I have declared a couple of middlewares in the app router, but these two are LAST ones:

app.use('/', adminRouter)
app.use(errorMiddleware)



via mpoureki

No comments:

Post a Comment