英文:
NestJS treats 2 different actions as the same in Guard
问题
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>("isPublicKey", [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
return super.canActivate(context);
}
}
@Get(':id')
findOneById(@Param('id') id: string) {
return this.storesService.findOne(id);
}
@Get('/current')
@SetMetadata("isPublicKey", true)
currentStore(@Req() request: any) {
console.log(request);
}
当我发送 GET 请求 http://127.0.0.1:8000/stores/current
时,反射器找不到标志 "isPublicKey"。但在上下文中,我看到一个带有另一个路径的路由对象。
如果我删除 findOneById
方法,那么一切都能正常工作,并且在上下文中的路由对象中,我看到与原始路由相同的正确路由。
英文:
Guard
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>("isPublicKey", [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
return super.canActivate(context);
}
}
2 get controllers with different paths.
@Get(':id')
findOneById(@Param('id') id: string) {
return this.storesService.findOne(id);
}
@Get('/current')
@SetMetadata("isPublicKey", true)
currentStore(@Req() request: any) {
console.log(request);
}
When I send get request http://127.0.0.1:8000/stores/current
reflector doesn't find the flag "isPublicKey". But In context, I see an object route with another path.
But if I delete the findOneById
method, then all works correctly, and in the route object in context, I see the correct route same as the original route.
答案1
得分: 3
改变方法的顺序。
如果你调用/current
,将会调用第一个匹配的方法。
在这种情况下,是/:id
(带有id 'current')。
英文:
Change the order of the methods.
If you call /current
, the first method that fits will be called.
In this case /:id
(with the id 'current')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论