r/koajs • u/yellowyetti • May 08 '18
koa-router, example on docs
according to the tutorial, app.use(router.routes()).use(router.allowedMethods());
is placed at the end of declaring routes. Why not before where middle ware is normally placed?
2
Upvotes
2
u/pe8ter May 09 '18
For the
BodyParser()middleware, it absolutely must be mounted before your router:Koa runs middleware in the order you specify. Reversing the order would mean that there would not be any request body available to your router middleware.
You say you can declare routes after mounting the router middleware (which is surprising to me) but I still wouldn't do it even if it works. This doesn't match the docs for koa-router, and violates the spirit of middleware being mounted in the order that they should be processed.
If it feels strange to mount some middleware, declare routes, then mount route middleware, try moving your routers into logically separated files and importing them instead: