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

想要在全局中间件中获取ctx._matchedRoute 有什么办法吗? #3009

Closed
9yuntu opened this issue Sep 15, 2018 · 6 comments
Closed

Comments

@9yuntu
Copy link

9yuntu commented Sep 15, 2018

需求:想在自定义的全局中间件里获取到 ctx._matchedRoute

部分代码

/app/middleware/test.js

console.log('ctx._matchedRoute',ctx._matchedRoute);
// 输出 ctx._matchedRoute : undefined

/config/config.default.js 配置

// 中间件
config.middleware = ['test'];

目前研究了一下,发现将test中间件单独挂载在某个路由上是能拿到 ctx._matchedRoute 的,这应该是egg的加载路由、中间件的顺序导致的。

但是还是不死心的想问问想要在全局中间件中获取ctx._matchedRoute 有什么办法吗?

@egg-bot
Copy link

egg-bot commented Sep 15, 2018

Translation of this issue:


Is there any way to get ctx._matchedRoute in the global middleware?

Requirements: I want to get ctx._matchedRoute in a custom global middleware

Part of the code

/app/middleware/test.js

Console.log('ctx._matchedRoute',ctx._matchedRoute);
// output ctx._matchedRoute : undefined

/config/config.default.js configuration

// middleware
Config.middleware = ['test'];

At present, I have studied it and found that the test middleware can be mounted on a certain route to get ctx._matchedRoute. This should be caused by the order of loading routes and middleware of egg.

But still do not give up want to ask ** Do you want to get ctx._matchedRoute in the global middleware? **

@atian25
Copy link
Member

atian25 commented Sep 15, 2018

XY 问题

还是来说说你的原始需求吧,是不是想做权限管理啥的?

@9yuntu
Copy link
Author

9yuntu commented Sep 15, 2018

好吧,原始需求

想自定义一个全局中间件,用于权限管理,代码如下

module.exports = (options, app) => {
	return async function aclMiddleware(ctx, next) {
		//获取当前请求所匹配的 path-pattern		
		console.log("ctx._matchedRoute : ",ctx._matchedRoute)
				
		const key = ctx.request.method.toString() + "__" + ctx._matchedRoute.toString();		
		
		const rights = await ctx.app.redis.get(key);

		console.log("rights", rights);

		if (rights) {
			console.log('权限验证成功');
			await next();
		} else {
			ctx.status = 422;
			ctx.body = {
				err: '没有权限',
				msg: '未授权的请求'
			};
		}


	}
};

其中ctx._matchedRoute 输出结果为undefined,想请问如何解决在全局中间件中获取path-pattern

@popomore
Copy link
Member

放到 router middleware 试试

app.get('/', app.middleware.aclMiddleware(), 'controller');

@9yuntu
Copy link
Author

9yuntu commented Sep 17, 2018

谢谢,放到 router middleware 是可以的

@9yuntu 9yuntu closed this as completed Sep 17, 2018
@atian25
Copy link
Member

atian25 commented Sep 17, 2018

执行顺序问题, global middleware -> router mapping -> router middleware -> controller

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

4 participants