代码之家  ›  专栏  ›  技术社区  ›  Samuel A. Souza

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

  •  0
  • Samuel A. Souza  · 技术社区  · 2 年前

    我正在学习使用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,这样我就可以在env中定义我的秘密。我该怎么做?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Jay McDoniel    2 年前

    config 作为参数传递给构造函数,因此可以删除 this 在里面 this.config 并且仍然访问 配置 很好