NestJS 无法解析 JWT_MODULE_OPTIONS 的依赖关系

Ник*_*тев 8 module typescript nestjs

我无法编译并出现此错误:

Nest 无法解析 JWT_MODULE_OPTIONS 的依赖关系(?)。请确保索引 [0] 处的参数在 JwtModule 上下文中可用。+52毫秒

我看到模块和服务存在类似的依赖关系问题,但它们对我不起作用。在我的auth.module.ts中使用 JwtModule :

import { JwtModule } from '@nestjs/jwt';
@Module({
    imports: [
        TypeOrmModule.forFeature([User, Role]),
        ConfigModule,
        PassportModule.register({ defaultStrategy: 'jwt' }),
        JwtModule.registerAsync({
            inject: [ConfigService],
            useFactory: async (configService: ConfigService) => ({
                secretOrPrivateKey: config.jwtSecret,
                type: configService.dbType as any,
                host: configService.dbHost,
                port: configService.dbPort,
                username: configService.dbUsername,
                password: configService.dbPassword,
                database: configService.dbName,
                entities: ['./src/data/entities/*.ts'],
                signOptions: {
                    expiresIn: config.expiresIn,
                },
            }),
        }),

    ],
    providers: [AuthService, JwtStrategy],
    controllers: [AuthController],
})
export class AuthModule { }
Run Code Online (Sandbox Code Playgroud)

我不知道如何修复这个错误...使用jwt 6.1.1

编辑:在我之前的项目中使用 jwt 6.0.0,所以我降级它,但问题没有解决。

Stu*_*ose 8

首先,您将 TypeORMModule 配置与 JWTModule 配置混合。

根据@nestjs/jwt 源代码(和文档secretOrPrivateKeysignOptions. 所有其他参数似乎都是 TypeORMModule 配置的一部分。

其次,ConfigService(JWT 模块的依赖项 [0])似乎不存在于代码中的任何位置。因此,您缺少对内部存在 ConfigService 的模块的导入。

这就是依赖项加载失败的原因(这就是抛出错误的含义)

请注意,在您的代码中缺少模块的导入(ConfigModule在以下示例中),该模块是保存 ConfigService 的模块。否则无法从任何地方注入这个ConfigService!

JwtModule.registerAsync({
  imports: [ConfigModule], // Missing this
  useFactory: async (configService: ConfigService) => ({
    signOptions: {
       expiresIn: config.expiresIn,
    },
    secretOrPrivateKey: config.jwtSecret,
  }),
  inject: [ConfigService], 
}),
Run Code Online (Sandbox Code Playgroud)