1. 主要环境
node v21.2.0
@nestjs/core ^10.2.10
展现一下全部依赖
2. 问题定位
出现问题的地方,在创建access_token时候出错
[Nest] 40264 - 2023/12/04 09:55:37 ERROR [ExceptionsHandler] secretOrPrivateKey must have a value
Error: secretOrPrivateKey must have a value
at Object.module.exports [as sign] (E:\nest-trpc\node_modules\jsonwebtoken\sign.js:111:20)
at JwtService.sign (E:\nest-trpc\node_modules\@nestjs\jwt\dist\jwt.service.js:41:20)
at AuthService.login (E:\nest-trpc\src\auth\auth.service.ts:30:44)
at UsersController.login (E:\nest-trpc\src\users\users.controller.ts:20:29)
at E:\nest-trpc\node_modules\@nestjs\core\router\router-execution-context.js:38:29
at E:\nest-trpc\node_modules\@nestjs\core\router\router-execution-context.js:46:28
at E:\nest-trpc\node_modules\@nestjs\core\router\router-proxy.js:9:17
3.解决方案
在检查N遍后,在stackoverflow找了半天没找到解决方法一步一步调试,发现不能按照官方文档这么写
官方文档原文:
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload), //这一步出现问题
};
}
这样改就行了
this.jwtService.sign(
payload,
{ secret: jwtConstants.secret } //添加你的secret
)