我是 koa 新手。我需要在 koa 请求中获取实际路线。
示例 1:如果我点击路线
/user
并且我得到 ctx 原始 url /user/
。
示例 2:如果我点击一条路线
user/:id
并且我得到 ctx 原始 url /user/1
。
我尝试获得像
这样的路径exports.checkAuth = async ctx => {
console.log(ctx.originalUrl); // return -> /user/1
console.log(ctx.path); // return -> /user/1
};
我想在每个请求中获得像
user/:id
这样的实际路线路径。
在快速路线中获得像这样的实际路径
app.get('/user/:id', function userIdHandler(req, res) {
console.log(req.route);
});
输出:
{ path: '/user/:id',
stack:
[ { handle: [Function: userIdHandler],
name: 'userIdHandler',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/?$/i,
method: 'get' } ],
methods: { get: true } }
在 koa.js 中,当路由匹配时,其路径可在
ctx._matchedRoute
获取,如果命名,则名称可在 ctx._matchedRouteName
获取
ctx._matchedRoute
-> 将在您的情况下返回 user/:id
请记住 ctx._matchedRoute 是
koa-router
的一部分。
一个好的方法是从 koa-router 添加到 ctx 的
ctx.matched
获取它,例如像这样的:
ctx.matched && ctx.matched.length>0 && ctx.matched[0].path || ""
到目前为止,简单使用 ctx._matchedRoute 的问题是,即使假设控制器不调用 next(),它将从第一个匹配的路由执行控制器函数,但它将包含最后一个匹配的路由。这是 koa-router 代码link.