我有一个像这样的自定义方法装饰器。
export function CustomDecorator() {
return applyDecorators(
UseGuards(JwtAuthGuard)
);
}
在自定义装饰器中,我想获取请求 header 但不确定如何获取请求实例?
最佳答案
您将无法在类或方法装饰器中获取 ExectuionContext
对象或 Request
对象,因为这些装饰器在导入时立即运行.相反,应该做的是制作一个 SuperGuard
,它确实有 ExecutionContext
可供使用。这个 SuperGuard
应该通过 constructor
将所有其他防护注入(inject)其中,并且根据 header ,您应该调用/返回被调用防护的结果。像这样的:
@Injectable()
export class SuperGuard implements CanActivate {
constructor(
private readonly jwtAuthGuard: JwtAuthGuard,
private readonly googleAuthGuard: GoogleAuthGuard,
) {}
canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest();
if (req.headers['whatever'] === 'google') {
return this.googleAuthGuard.canActivate(context);
} else {
return this.jwtAuthGuard.canActivate(context);
}
}
}
关于decorator - 在 NestJS 中,如何在自定义方法装饰器中获取执行上下文或请求实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63496404/