【问题标题】:How can I user configService in super()?如何在 super() 中使用 configService?
【发布时间】:2022-01-11 18:38:15
【问题描述】:

我有一个关于设置环境变量的问题。

在官方文档中,它说在这种情况下使用 ConfigModule,但我的情况是例外情况。

因为我想在构造函数的 super() 中使用它。

我的代码如下。

这种情况有什么解决办法吗?

如果您需要更多信息,请告诉我。

感谢大家的支持!!

// jwt.strategy.ts

import { UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserRepository } from './user.repository';
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        @InjectRepository(UserRepository)
        private userRepository: UserRepository,
        private configService: ConfigService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: configService.get('JWT_TOKEN'),
        });
    }

    async validate(payload: JwtPayload) {
        const { username } = payload;
        const user = await this.userRepository.findOne({ username });

        if (!user) {
            throw new UnauthorizedException();
        }
        return user;
    }
}

【问题讨论】:

标签: nestjs nestjs-config nestjs-passport nestjs-jwt


【解决方案1】:

对于您的 Strategy,您缺少 @Injectable(),它告诉 Nest 它需要注入构造函数中定义的依赖项。

【讨论】:

    【解决方案2】:

    您需要将 configModule 导入到您的模块类中才能使 configService 工作。此外,在类名上方添加 @Injectable() 以表明它是提供者。

    这是您导入模块的方式。

    //auth.module.ts    
        
    import { Module } from '@nestjs/common';
    import { ConfigModule } from '@nestjs/config';
    import { JwtStrategy } from './jwt.strategy';
    
    @Module({
      imports: [ConfigModule],
      provider:[JwtStrategy]
    })
    export class AuthModule {}
    

    NestJs 解决了它们之间的依赖关系。

    见:https://docs.nestjs.com/techniques/configuration#using-the-configservice

    【讨论】:

      【解决方案3】:

      我还想指出,由于您没有在任何地方使用configService,而是在super()调用中使用private前面的关键字是多余的

      您可以尝试使用this.configService.get('JWT_TOKEN'),但它只会对您大喊大叫,说您没有调用 super

      删除 private 关键字只会避免将 configService 作为类变量,而只是将其视为传递给它的某个选项

      【讨论】:

      • 这应该是正确的答案。因为您无法在super 调用中访问this,所以删除private 关键字并通过configService.get('JWT_TOKEN') 获取配置。
      猜你喜欢
      • 2021-01-18
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 2022-06-17
      • 1970-01-01
      • 2019-03-05
      • 2022-07-14
      相关资源
      最近更新 更多