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

NestJs调用jwtService.decode报错:Cannot read properties of undefined

NestJs中调用JwtService.decode报错:Cannot read properties of undefined (reading 'decode')

报错信息

[Nest] 16960 - 2022年12月19日 晚上10:22:28 ERROR [ExceptionsHandler]
Cannot read properties of undefined (reading 'decode') TypeError:
Cannot read properties of undefined (reading 'decode')

在 AdminGuard.canActivate (D:\Noum\Data\CYBRNODE\MAN STACK\Cybrnode-Blog-Backend\Cybr-Blog-Nest-Backend\src\guard\admin.guard.ts:28:34)

在 GuardsConsumer.tryActivate (D:\Noum\Data\CYBRNODE\MAN STACK\Cybrnode-Blog-Backend\Cybr-Blog-Nest-Backend\node_modules@nestjs\core\guards\guards-consumer.js:15:34)
在 processTicksAndRejections (node:internal/process/task_queues:96:5)

相关代码

类型定义

export type PayloadType = {
  id: string;
};

业务代码

let jwtService: JwtService;

let token = AuthenticationService.jwtToken.accessToken;
console.log(token);

if (token) {
  const payload = jwtService.decode(token.split('')[1]) as PayloadType;
  console.log(payload);
}

解决方案

  • 修复JwtService未实例化问题
    你仅声明了jwtService的类型但未创建有效实例,Nest框架中必须通过构造函数依赖注入获取JwtService实例,修改AdminGuard代码如下:

    import { Injectable, ExecutionContext } from '@nestjs/common';
    import { JwtService } from '@nestjs/jwt';
    
    @Injectable()
    export class AdminGuard {
      // 通过构造函数注入JwtService实例
      constructor(private readonly jwtService: JwtService) {}
    
      async canActivate(context: ExecutionContext): Promise<boolean> {
        let token = AuthenticationService.jwtToken.accessToken;
        console.log(token);
    
        if (token) {
          // 使用注入的实例调用decode方法
          const payload = this.jwtService.decode(token.split(' ')[1]) as PayloadType;
          console.log(payload);
        }
        // 补充其他守卫逻辑...
        return true;
      }
    }
    
  • 修复Token分割错误
    原代码中token.split('')[1]是按单个字符分割,会错误取到token的第二个字符。标准Bearer Token格式为Bearer xxxxxxxxxx,需按空格分割取第二部分,改为token.split(' ')[1]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:45:24