[eggjs/egg]_matchedRouteName的生成时间

2024-07-22 848 views
9

问题描述: 最近用egg做项目的时候 准备自己写一个权限管理中间件,使用的是router.resources配置路由,网上查到_matchedRouteName这个参数匹配的是resources的router_name 期望在请求进入时获取到这个参数,然后在我的配置文件里面查 该角色是否具有这个router_name的权限,但是这个参数我测试发现进入controler之后才能获取到,中间件里没有值。所以我现在面临的问题时要么自己去写url匹配的规则,要么就在controller里调用处理方法,但是这都不是我想要的。所以想问下有没有什么其他办法提前获取这个值

回答

6

因为这是 router 的职责,而 router 是最里面的一个 middleware,你在外面的 middleware 的进入阶段肯定是拿不到的。

你可以看下 egg-router 的源码

2

非常感谢,我找时间去看下router的源码。 不过这样的话我估计我只能写个工具函数单独每个controller处理了。

9

你可以这样:

// app/router.js
module.exports = app => {
  const { router, controller } = app;

  router.use((ctx, next) => {
    console.log(ctx.routerName, ctx.routerPath, ctx._matchedRouteName);
    return next();
  });

  router.get('home', '/', controller.home.index);
};
9

Ok 我试试 bty 大佬你这回复速度可以啊 开挂了把

0
module.exports = () => {
  return async (ctx, next) => {
    const { router, path, method } = ctx;
    const matched = router.match(path, method); // { pathAndMethod: [], path: [], route: true }
    const { pathAndMethod: [ first ] } = matched; // [{ path: routerPath, methods: [] }]
    const { path: routerPath } = first;
    ctx.app.logger.debug('[middleware.acl]', method, routerPath);
    await next();
  };
};
6

楼上你这方法相当于重新执行一次匹配,有点浪费性能。

5
4220