NestJS JWT 策略:在派生类的构造函数中访问“this”之前必须调用“super”

问题描述 投票:0回答:1

我正在学习使用 JWT 使用 NestJS 创建身份验证系统。我的系统有一个用于管理用户的 CRUD,但它只能由经过身份验证的人使用,所以我设置了这个防护:

@Controller('users')
@UseGuards(AuthGuard('jwt'))
export class UsersController {
    \\ implementation
}

我正在尝试创建 JWT 策略:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: this.config.get<string>('JWT_SECRET_PASS'),
    });
  }
}

但是面临错误:

'super' must be called before accessing 'this' in the constructor of a derived class.

我需要访问 ConfigService,以便我可以定义环境中的秘密。我怎样才能做到这一点?

authentication jwt nestjs passport.js
1个回答
0
投票

config
作为参数传递给构造函数,因此您可以删除
this
中的
this.config
,但仍然可以访问
config
就好了

© www.soinside.com 2019 - 2024. All rights reserved.