Open Mensu opened 6 years ago
As a workaround, in my personal toy projects I would turn to koa-express-router
, which is based on Express
's Router, and doesn't have problems with shared nested routers
, param issues
, use issues
, etc.
I've also investigated impress-router
, koa-Router
and koa-router2
before, only to find they don't seem to support .param
, which feature has been widely used in some projects I am working for, and we still decide to use this most popular koa-router
package in the community in future.
So I still expect to get a response about this issue: are those behaviors due to some intentional design, or just due to a bug for which it is possible to find workarounds without switching to other router packages?
This is a bug. The router objects are mutable and calling prefix
or use('prefix', subRtr)
will mutate the original and break some assumptions about how that router will work. See #244
behavior 1
When I make a request of
GET /top/1/sub
to a server written in the following codes, I get a confusing response.Response:
As we can see,
topRtrParam
is called twice during one request. But I expecttopRtrParam
to be called only once.Is this an intentional design? How I should avoid this to get my expected response?
Digging into the source code of
koa-router
I find that it is because, whentopRtr.use('/top/:id/sub', subRtr.routes())
, inhttps://github.com/alexmingoia/koa-router/blob/afb542bd9fbeec43f455f22b569c6e374a497dc8/lib/router.js#L272
topRtrParam
is added to bothsubRtrAll
andsubRtrGet
. Thestack
s ofsubRtrAll
andsubRtrGet
('sLayer
) both containtopRtrParam
.Therefore, when a request for
GET /top/1/sub
comes, inhttps://github.com/alexmingoia/koa-router/blob/afb542bd9fbeec43f455f22b569c6e374a497dc8/lib/router.js#L347
topRtrParam
would be included intolayerChain
twice by the concatenation involvinglayer.stack
s, namely[topRtrParam, subRtrAll]
and[topRtrParam, subRtrGet]
.behavior 2
Besides, I find that when I change
to
I get response:
In the first call of
topRtrParam
id receivesundefined
!Digging into the source code I found it is because
ignoreCaptures
would be set totrue
(!hasPath
) whensubRtr.use(subRtrAll)
https://github.com/alexmingoia/koa-router/blob/afb542bd9fbeec43f455f22b569c6e374a497dc8/lib/router.js#L276
while
ignoreCaptures
would not be set whensubRtr.get('/', subRtrGet)
https://github.com/alexmingoia/koa-router/blob/afb542bd9fbeec43f455f22b569c6e374a497dc8/lib/router.js#L202
Is this made intentionally? I could just add a string path like '*' to avoid this, but I believe the expected response should still be
Thanks for any help in advance.