The ctx. _matchedRoute is not the route I requested!
BainDragneel opened this issue · comments
node.js version: 12.12.0
npm/yarn and version: 6.11.3
koa-router
version: 7.4.0
koa
version: 2.10.0
hi,I have some problems. I use koa tag 2.7.0 .
Now I have two routes, one is "/api/order/list" and another is "/api/order/:orderId" .
I want to log each request. When I request the second interface with params, I want the url I am recording to be the url of my own defined api, not the url directly with params.For example, when I request "http://127.0.0.1:3000/api/order/57d52c52403f2ee865738ec7", I want to record that the url is "/api/order/:orderId" instead of "/api/order/57d52c52403f2ee865738ec7".
But ctx.url ctx. originalUrl is not what I want, and ctx. _matchedRoute is what I want.However, I have a new problem. When I request "/api/order/list", the value of ctx._matchedRoute is still "apr/order/:orderId" instead of "/api/order/list" and ctx.matched is an array of two object elements.
Why the _matchedRoute is not the route I requested?
Code sample:
I have found something that may help.
node_modules\koa-router\lib\router.js
335 var mostSpecificLayer = matchedLayers[matchedLayers.length - 1];
336 ctx._matchedRoute = mostSpecificLayer.path;
As shown in the code, ctx._matcheRoute is the most matched route path insteadof requested.
I ran into the same problem. The issue is, that matchedLayers contains - as the name suggests - all matched layers, that will be put in the middleware-chain (because the regex matches).
In the case above, it's because :orderId
could also be list
. So, if the orderId-Middleware decides, it doesn't want to handle the request, it can call next()
and the list-route will be called. That way the "mostSpecificLayer" isn't necessarily the "last" or "current" one.
With that being said, the ctx._matchedRoute
is probably a bug - or at least misleadingly named.
I've created PR #524, which would populate ctx.routerPath
@schwarmco this is the official one from koa org https://github.com/koajs/router , a fork of this repo
@tuananh thanks - i opened a pull-request there... just landed here, because i searched for this exact same issue :)
Thanks very much, I have some things I did not pay attention to this issue in time, sorry!
Already got help:https://github.com/koajs/router/releases/tag/v9.1.0 Thx!!!!!