Nest 无法解析 JwtService (?) [JWT_MODULE_OPTIONS] 的依赖项
Posted
技术标签:
【中文标题】Nest 无法解析 JwtService (?) [JWT_MODULE_OPTIONS] 的依赖项【英文标题】:Nest can't resolve dependencies of the JwtService (?) [JWT_MODULE_OPTIONS] 【发布时间】:2021-11-24 06:48:33 【问题描述】:我收到此错误
[Nest] 24356 - 10/03/2021, 11:19:31 AM LOG [NestFactory] Starting Nest application...
[Nest] 24356 - 10/03/2021, 11:19:31 AM LOG [InstanceLoader] PrismaModule dependencies initialized +51ms
[Nest] 24356 - 10/03/2021, 11:19:31 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtService context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtService?
- If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtService?
@Module(
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
)
Error: Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0] is available in the JwtService context.
Potential solutions:
- If JWT_MODULE_OPTIONS is a provider, is it part of the current JwtService?
- If JWT_MODULE_OPTIONS is exported from a separate @Module, is that module imported within JwtService?
@Module(
imports: [ /* the Module containing JWT_MODULE_OPTIONS */ ]
)
at Injector.lookupComponentInParentModules (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:193:19)
at Injector.resolveComponentInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:149:33)
at resolveParam (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:103:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:118:27)
at Injector.loadInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:47:9)
at Injector.loadProvider (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:69:9)
at async Promise.all (index 0)
at InstanceLoader.createInstancesOfProviders (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/instance-loader.js:44:9)
at /home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/instance-loader.js:29:13```
我尝试在输入某些路由时使用中间件对用户进行身份验证
auth.middleware.ts
import Request, Response, NextFunction from 'express';
import JwtService from '@nestjs/jwt';
@Injectable()
export class AuthMiddleware implements NestMiddleware
constructor(private jwtService: JwtService)
use(req: Request, res: Response, next: NextFunction)
const headerToken = req.headers.authorization;
if (!headerToken)
return res.status(401).send( error: 'No token provided' );
const [scheme, token] = headerToken.split(' ');
if (!token)
return res.status(401).send( error: 'Token error' );
try
const user = this.jwtService.verify(token);
req.user = user.id;
return next();
catch (error)
return res.status(401).send( error: 'Invalid token' );
```
auth.module.ts
import Module from '@nestjs/common';
import JwtModule, JwtService from '@nestjs/jwt';
import AuthMiddleware from './auth.middleware';
@Module(
imports: [
JwtService,
JwtModule.register(
secret: process.env.JWT_SECRET,
signOptions: expiresIn: '1day' ,
),
],
providers: [AuthMiddleware],
exports: [AuthMiddleware],
)
export class AuthModule
我不是 100% 确定中间件应该有一个没有它的模块,中间件将无法工作
app.module.ts
import MiddlewareConsumer, Module, NestModule from '@nestjs/common';
import AppController from './app.controller';
import AppService from './app.service';
import PrismaModule from './prisma.module';
import UsersModule from './users/users.module';
import ConnectionsModule from './connections/connections.module';
import MessagesModule from './messages/messages.module';
import AuthModule from './auth/auth.module';
import AuthMiddleware from './auth/auth.middleware';
@Module(
imports: [
PrismaModule,
UsersModule,
ConnectionsModule,
MessagesModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
)
export class AppModule implements NestModule
configure(consumer: MiddlewareConsumer)
consumer.apply(AuthMiddleware).forRoutes('users');
文档说我需要在此处传递这些选项才能使中间件工作
如果我尝试从 auth.module.ts 中的导入中删除 JwtService,我会得到:
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] PrismaModule dependencies initialized +45ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] JwtModule dependencies initialized +0ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] MessagesModule dependencies initialized +0ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] AuthModule dependencies initialized +0ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] UsersModule dependencies initialized +0ms
[Nest] 28995 - 10/03/2021, 12:50:31 PM LOG [InstanceLoader] ConnectionsModule dependencies initialized +0ms
(node:28995) UnhandledPromiseRejectionWarning: Error: Nest can't resolve dependencies of the class AuthMiddleware
constructor(jwtService)
this.jwtService = jwtService;
use(req, res, next)
const headerToken = req.headers.authorization;
if (!headerToken)
return res.status(401).send( error: 'No token provided' );
const [scheme, token] = headerToken.split(' ');
if (!token)
return res.status(401).send( error: 'Token error' );
try
const user = this.jwtService.verify(token);
req.user = user.id;
return next();
catch (error)
return res.status(401).send( error: 'Invalid token' );
(?). Please make sure that the argument JwtService at index [0] is available in the AppModule context.
Potential solutions:
- If JwtService is a provider, is it part of the current AppModule?
- If JwtService is exported from a separate @Module, is that module imported within AppModule?
@Module(
imports: [ /* the Module containing JwtService */ ]
)
at Injector.lookupComponentInParentModules (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:193:19)
at Injector.resolveComponentInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:149:33)
at resolveParam (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:103:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:118:27)
at Injector.loadInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:47:9)
at Injector.loadMiddleware (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/injector/injector.js:56:9)
at MiddlewareResolver.resolveMiddlewareInstance (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/middleware/resolver.js:16:9)
at async Promise.all (index 0)
at MiddlewareResolver.resolveInstances (/home/luisfelipe/Projects/message-service/node_modules/@nestjs/core/middleware/resolver.js:13:9)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28995) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28995) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
如果我尝试在 appModule 上导入 JwtModule 或 JwtService,它会返回与之前相同的错误
我的问题是:我需要导入 JwtService 以在身份验证中间件中使用它,如果我不导入,它说我应该导入它。如果我导入它会返回有关 JWT_MODULE_OPTIONS 的错误
这是我关心的问题还是来自 @nestjs/jwt 的错误,如果这是我创建的错误,我该如何修复它?
整个应用在:https://github.com/akaLuisinho/chat-app
【问题讨论】:
【参考方案1】:从您的AuthModule
的imports
中删除JwtService
。提供者从不属于imports
数组,并且因为您已经导入了JwtModule
,所以您不需要将JwtService
添加到任何模块,JwtModule` 已经公开了对它的访问。
【讨论】:
以上是关于Nest 无法解析 JwtService (?) [JWT_MODULE_OPTIONS] 的依赖项的主要内容,如果未能解决你的问题,请参考以下文章
Nest 无法解析 PhotoService 的依赖关系(?)
Nest.js 在单元测试中无法解析 Mongoose 模型依赖