You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS子模块注入ConfigService为undefined问题如何解决

问题根因

JwtStrategy类缺少@Injectable()装饰器,导致NestJS无法为其解析构造函数的依赖注入。
NestJS的依赖注入容器只会对被@Injectable()标记的类执行依赖解析逻辑,你当前的JwtStrategy没有添加该装饰器,容器实例化这个类时不会自动传入ConfigService实例,因此构造函数中拿到的configService值为undefined。
另外你已经将ConfigModule配置为全局模块(isGlobal: true),两处冗余配置可以清理:

  • AppModule的exports数组中不需要额外导出ConfigModule,全局模块注册后所有子模块可直接使用其提供的服务
  • AuthModule的imports数组、JwtModule.registerAsync()配置的imports数组中都不需要重复导入ConfigModule
修复步骤
  1. 修改jwt.strategy.ts,导入@Injectable装饰器并标记到JwtStrategy类上,修正后的代码如下:
// 新增这行导入
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import {ConfigService} from "@nestjs/config";

// 新增@Injectable()装饰器
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    // 建议给构造函数参数添加private修饰符,符合TypeScript类属性简写规范
    constructor(private configService: ConfigService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: configService.get('jwt').secret,
        })
    }

    async validate(payload: any) {
        return {userId: payload.sub, email: payload.email}
    }
}
  1. (可选)清理前面提到的冗余配置,不清理也不会影响功能正常运行。

修改后重新启动项目,JwtStrategy中就能正常获取到ConfigService实例了。


内容的提问来源于stack exchange,提问作者Sancho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 07:24:37