Nest 无法解析 JwtService 的依赖关系(?)[JWT_MODULE_OPTIONS]

Luí*_*lva 5 authentication middleware node.js jwt nestjs

我收到这个错误


[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```
Run Code Online (Sandbox Code Playgroud)

我尝试在输入某些路由时使用中间件对用户进行身份验证

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' });
    }
  }
}```


Run Code Online (Sandbox Code Playgroud)

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 {}
Run Code Online (Sandbox Code Playgroud)

我不能 100% 确定中间件应该有一个模块,但如果没有它,中间件将无法工作

应用程序模块.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');
  }
}
Run Code Online (Sandbox Code Playgroud)

文档说我需要在此处传递这些选项才能使中间件正常工作

如果我尝试从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.```
Run Code Online (Sandbox Code Playgroud)

如果我尝试在 appModule 上导入 JwtModule 或 JwtService,它会返回与之前相同的错误

我的问题是:我需要导入 JwtService 以便在身份验证中间件中使用它,如果我不导入,它会说我应该导入它。如果我导入它会返回有关 JWT_MODULE_OPTIONS 的错误

这是我关心的问题还是@nestjs/jwt的错误,如果这是我创建的错误,我该如何修复它?

整个应用程序位于: https: //github.com/akaLuisinho/chat-app

Jay*_*iel 2

JwtService从你AuthModule的中删除imports。提供程序永远不属于imports数组,并且因为您已经导入JwtModule,所以不需要添加JwtService到任何模块,JwtModule`已经公开了对其的访问。