Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested router's middleware has no access to request params #122

Open
egorovli opened this issue Jun 30, 2021 · 4 comments
Open

Nested router's middleware has no access to request params #122

egorovli opened this issue Jun 30, 2021 · 4 comments

Comments

@egorovli
Copy link

node.js version: 16.2.0
yarn version: 1.22.10
@koa/router version: 10.0.0
koa version: 2.13.1

Code sample:

let usersRouter = new Router()
  .use(async (ctx, next) => {
    console.log(ctx.params.userId ?? 'No user ID in params')
    return next()
  })
  .get('/', async (ctx, next) => {
    ctx.body = {
      id: 1,
      name: 'John Doe'
    }
  })

export let router = new Router()
  .use('/users/:userId', usersRouter.routes(), usersRouter.allowedMethods())

Expected Behavior:

The middleware prints userId to console.

Actual Behavior:

The middleware prints 'No user ID in params' because ctx.params.userId is undefined.

Additional steps, HTTP request details, or to reproduce the behavior or a test case:

This is actually fixed by calling .use() with an empty path 🤷‍♂

let usersRouter = new Router()
  // Here an empty path is used. Previosly it was omitted.
  .use('', async (ctx, next) => {
    console.log(ctx.params.userId ?? 'No user ID in params')
    return next()
  })
  .get('/', async (ctx, next) => {
    ctx.body = {
      id: 1,
      name: 'John Doe'
    }
  })

export let router = new Router()
  .use('/users/:userId', usersRouter.routes(), usersRouter.allowedMethods())
@3imed-jaberi
Copy link
Member

I have a quick solution to fix this behave but it's break 2 test case

  • Layer > Layer#match() > populates ctx.captures with regexp captures include undefiend:
  • Router > matches corresponding requests with optional route parameter:

My Solution:

  // add this line inside the [Router.prototype.use] function just before the hasPath checking.
  if (middleware.length === 1) path = middleware.unshift('');

@miwnwski, what do you think here ?!

@miwnwski
Copy link
Member

I actually don't use Koa-router so I have very little insight. @niftylettuce probably has more to say about this than I do I'm afraid.

@niftylettuce
Copy link
Contributor

@3imed-jaberi im open to that 100%

@krosenk729
Copy link

following as we have the same issue... is there a workaround or fix for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants