ZijianHe / koa-router

Router middleware for koa.
MIT License
4.85k stars 407 forks source link

Middleware gets `ctx.params` for all routes #347

Open zhuscat opened 7 years ago

zhuscat commented 7 years ago

I have a middleware(let's call it mw) which will use ctx.params to get the parameter in a path.

If I write:

router.use(mw)

The ctx.params in the mw is {}

But if I write:

router.use([
  '/example/:id',
  '/example2/:id',
], mw)

The ctx.params in the mw is { id: 'some_id' }

I want my middleware to be called for every route and I want to get the right ctx.params.

Is there any way to solve this problem?

klerick commented 7 years ago

after init router router.stack.forEach(routerItem => routerItem.stack.unshift(mw))

mmazzarolo commented 7 years ago

Does a cleaner way to do this exist?

uinz commented 6 years ago

@zhuscat

const router = new Router({
  prefix: "/users/:id",
})

// GET /users/123
router.use("*", async (ctx, next) => {
  // ctx.params = {id: "123"}
  await next()
})