如何解决NestJS-未加载JWT依赖关系
我不需要完整的护照,我只需要签署JWT令牌。
我尝试使用此repository 我尝试了所有可能的组合,但无法将其集成到项目中。我遵循了几个不同的错误的过程。我修复了一个,然后弹出另一个。因此,我包括最小的部分以及当前抛出的错误。
AuthModule:
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { JwtService } from '@nestjs/jwt';
@Module({
imports: [ JwtModule.register({ secret: 'hard!to-guess_secret' })],providers: [AuthService],exports: [AuthService,JwtService]
})
export class AuthModule {}
AuthService:
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,) {}
async signPayload (user: any) {
const payload = { username: 'HARDCORE',color:'RED' };
return {
whatever: this.jwtService.sign(payload),};
}
}
AppModule:
@Module({
imports: [
ConfigModule.forRoot(),JwtModule.registerAsync({
imports: [ConfigModule],useFactory: async (configService: ConfigService) => ({
secret: 'wefwefwef',}),inject: [ConfigService],TypeOrmModule.forRoot({
type: 'mysql',...
}),UsersModule,SubscriptionsModule,ProductsModule
],controllers: [AppController],providers: [AppService],})
export class AppModule {
}
SomeController:
export class UsersController {
constructor(private readonly usersService: UsersService,private readonly authService: AuthService
) {}
...
@ApiResponse({ status: 401,description: 'Unauthorized.' })
@ApiResponse({ status: 404,description: 'User Not Found.' })
@Get('users')
async findOne(@Query() userGetDto: UserGetDto): Promise<User> {
const user = await this.usersService.findByUsername(userGetDto.userName);
if (!user) throw new NotFoundException('User Not Found')
let signedUser = this.authService.signPayload(user);
return user;
这是我得到的此设置的错误:
嵌套无法解析JwtService的依赖项(?)。请做出来 确保索引[0]处的参数JWT_MODULE_OPTIONS可用于 JwtService上下文。
我在这上面花了很多时间,但是我无法使它工作。
解决方法
根据您的错误,JwtService
在imports
数组中的某个位置。提供程序(标记为@Injectable()
的类)永远不会进入imports
数组,而应该添加到exports
数组中,并且应该将添加了exports
的模块放入在使用模块的imports
数组中。
此外,如果您正在使用动态模块(使用register
或forRoot
或两者的异步变体的任何模块),则应始终导出模块而不是其服务,因为该模块很可能具有服务正常运行所必需的重要配置。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。