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

NestJS中间件使用JwtService报错,请求技术帮助

JwtService注入中间件时出现undefined错误排查

问题背景

在UserModule中注册JwtModule后,给所有GET请求绑定CurrentAuth中间件,中间件内注入JwtService并调用其verify方法时,运行时报错:TypeError: Cannot read properties of undefined (reading 'verify')。

代码示例

1. UserModule的模块注册代码

@Module({
  imports: [
    // MongooseModule.forFeature([{ name: User.name, schema: userSchema }]),
    
    JwtModule.register({
      secret: process.env.JWT_TOKEN,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  controllers: [UserController],
  providers: [UserService, UserRepository],
  exports: [UserService, UserRepository],
})

2. UserModule的中间件注册代码

export class UserModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CurrentAuth).forRoutes({
      path: '*',
      method: RequestMethod.GET,
    });
  }
}

3. CurrentAuth中间件代码

export class CurrentAuth implements NestMiddleware {
  constructor(private tokenService: JwtService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const payload = this.tokenService.verify("mytoken");

    next();
  }
}

错误信息

TypeError: Cannot read properties of undefined (reading 'verify')

解决方案

问题核心是Nest中间件默认不会被DI容器管理,直接在构造函数中注入JwtService会导致依赖未被正确初始化,出现undefined。

修复步骤

将CurrentAuth中间件添加到UserModule的providers数组中,让Nest的DI容器负责中间件实例化及依赖注入:

@Module({
  imports: [
    // MongooseModule.forFeature([{ name: User.name, schema: userSchema }]),
    
    JwtModule.register({
      secret: process.env.JWT_TOKEN,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  controllers: [UserController],
  providers: [UserService, UserRepository, CurrentAuth], // 新增CurrentAuth到providers
  exports: [UserService, UserRepository],
})
export class UserModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CurrentAuth).forRoutes({
      path: '*',
      method: RequestMethod.GET,
    });
  }
}

补充说明

  • 确保process.env.JWT_TOKEN已正确配置,避免JwtService初始化失败;
  • 如果中间件需要在多个模块复用,可将其封装为独立模块并导出,再在目标模块中导入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:20:36