为啥 jwtService 未定义?

Posted

技术标签:

【中文标题】为啥 jwtService 未定义?【英文标题】:Why jwtService is undefined?为什么 jwtService 未定义? 【发布时间】:2021-07-22 11:35:57 【问题描述】:

JwtAuthGuard 我从标头验证令牌:

import  JwtService  from '@nestjs/jwt';
import 
  CanActivate,
  ExecutionContext,
  UnauthorizedException
 from '@nestjs/common';
import  Observable  from 'rxjs';

export class JwtAuthGuard implements CanActivate 
  constructor(private jwtService: JwtService) 

  canActivate(
    context: ExecutionContext
  ): boolean | Promise<boolean> | Observable<boolean> 
    const req = context.switchToHttp().getRequest();

    try 
      const authHeader = req.headers.authorization;
      const token = authHeader.split(' ')[1];

      const user = this.jwtService.verify(token);

      req.user = user;
      return true;
     catch (error) 
      console.log(error);
      throw new UnauthorizedException();
    
  

我的控制器:

import  Controller, Get, UseGuards  from '@nestjs/common';
import  JwtAuthGuard  from 'src/auth/jwt-auth.guard';
    
 @Controller('api/messages')
 export class MessagesController 
  @UseGuards(JwtAuthGuard)
  @Get()
   getAllUserMessages() 
     return "it's work";
     
  

我注册 JWT 的 AuthModule:

import  Module  from '@nestjs/common';
import  AuthService  from './auth.service';
import  AuthController  from './auth.controller';
import  UsersModule  from 'src/users/users.module';
import  JwtModule  from '@nestjs/jwt';
import  ConfigService  from '@nestjs/config';

@Module(
  providers: [AuthService],
  controllers: [AuthController],
  imports: [
    UsersModule,
    JwtModule.registerAsync(
      useFactory: async (configService: ConfigService) => (
        secret: configService.get('AUTH_KEY'),
        signOptions: 
          expiresIn: '12h'
        
      ),
      inject: [ConfigService]
    )
  ],
  exports: [JwtModule, AuthService]
)
export class AuthModule 

当我使用令牌去路由 /api/messages 时,我收到错误:

TypeError: Cannot read property 'verify' of undefined
at JwtAuthGuard.canActivate (/Users/alexander/Projects/nest/paska/dist/auth/jwt-auth.guard.js:18:42)

【问题讨论】:

【参考方案1】:

你的守卫缺少@Injectable() 装饰器。添加它,它将起作用。

【讨论】:

以上是关于为啥 jwtService 未定义?的主要内容,如果未能解决你的问题,请参考以下文章

为啥在函数体内定义的内置类型的未初始化对象具有未定义的值?

为啥未定义 selectedimage?

为啥VC++编译器提示标识符未定义?

为啥 Firebug 不为未定义的属性显示“未捕获的类型错误”?

为啥成员未定义?

为啥这个异步函数返回未定义? [复制]