gpt4 book ai didi

Nest can't resolve dependencies of the JwtAuthGuard(Nest无法解析JwtAuthGuard的依赖项)

转载 作者:bug小助手 更新时间:2023-10-25 21:55:50 24 4
gpt4 key购买 nike



I have a NestJS application with a JwtAuthGuard that I'm trying to use to protect an endpoint. The JwtAuthGuard is responsible for authenticating and authorizing requests based on JWT tokens.

我有一个带有JwtAuthGuard的NestJS应用程序,我正尝试使用它来保护端点。JwtAuthGuard负责基于JWT令牌对请求进行身份验证和授权。


import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { AuthService } from 'src/auth/auth.service';

@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private readonly authService: AuthService) {}

canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
return true;
}
}

I tried to use it on this endpoint

我尝试在此端点上使用它


  @Get('/user-data')
@UseGuards(JwtAuthGuard)
userData(@Req() req: Request) {
const jwt = req.cookies['jwt'];
return { jwt };
}

but it throws this error

但是它抛出了这个错误


ERROR [ExceptionHandler] Nest can't resolve dependencies of the JwtAuthGuard (?). Please make sure that the argument dependency at index [0] is available in the AuthModule context.

Potential solutions:
- Is AuthModule a valid NestJS module?
- If dependency is a provider, is it part of the current AuthModule?
- If dependency is exported from a separate @Module, is that module imported within AuthModule?
@Module({
imports: [ /* the Module containing dependency */ ]
})

This error suggests that there's an issue with the dependency injection in the JwtAuthGuard constructor. Specifically, it's unable to resolve the AuthService dependency.
even though I exported the AuthService
and refreshed everything

此错误表明JwtAuthGuard构造函数中的依赖项注入存在问题。具体地说,它无法解析AuthService依赖。即使我导出了AuthService并刷新了所有内容


Auth Module:

身份验证模块:


import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PrismaModule } from 'src/prisma/prisma.module';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';
import { PassportModule } from '@nestjs/passport';
import { JwtService } from '@nestjs/jwt';

@Module({
controllers: [AuthController],
providers: [AuthService, GoogleStrategy, JwtService],
imports: [
PrismaModule,
PassportModule.register({ defaultStrategy: 'google' }),
],
exports: [AuthService],
})
export class AuthModule {}


App Module:

应用程序模块:


import { Module, ValidationPipe } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { APP_PIPE } from '@nestjs/core';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { AuthService } from './auth/auth.service';
import { PrismaService } from './prisma/prisma.service';

@Module({
imports: [
ConfigModule.forRoot(),
AuthModule,
JwtModule.register({
secret: process.env.TOKEN,
signOptions: { expiresIn: '30d' },
}),
],
providers: [
AuthService,
PrismaService,
JwtService,
{
provide: APP_PIPE,
useClass: ValidationPipe,
},
],
})
export class AppModule {}

What is the problem

有什么问题吗?


the problem is here

问题就在这里


constructor(private readonly authService: AuthService) {}

if I remove this line it will work!

如果我删除这条线,它将工作!


The problem seems to revolve around the AuthService not being injected correctly into the JwtAuthGuard. If I remove the constructor line constructor(private readonly authService: AuthService) {}, the error goes away, but this is not a solution to the problem.

该问题似乎与未正确插入JwtAuthGuard的AuthService有关。如果我删除构造函数行构造函数(私有只读authService:AuthService){},错误就会消失,但这不是问题的解决方案。


I hope this additional information helps provide a clearer picture of the issue I'm facing with my NestJS application. If you have any suggestions or solutions, please feel free to share.

我希望这些附加信息有助于更清楚地了解我的NestJS应用程序所面临的问题。如果您有任何建议或解决方案,请随时分享。


更多回答

Can you add the AuthService to the post as well? Usually when dependency is shown in the error there's a circular import error somewhere

您可以将AuthService也添加到帖子中吗?通常,当依赖项显示在错误中时,表示某个地方存在循环导入错误

优秀答案推荐

Add JwtAuthGuard as provider in AuthModule.

在AuthModule中添加JwtAuthGuard作为提供程序。



Remove JwtService from the provider array and add JwtStratagy (create one if you have not)

从提供程序数组中删除JwtService并添加JwtStratagy(如果没有,请创建一个)


Adding JwtService to the provider will cause a circular dependency error

将JwtService添加到提供程序将导致循环依赖错误



Try removing JwtService from AuthModule and your AuthService look like constructor( @InjectRepository(User) private readonly userRepository: Repository<User>, private jwtService: JwtService, private configService: ConfigService, ) {}

尝试从AuthModule中删除JwtService,您的AuthService看起来像构造函数(@InjectRepository(User)私有只读用户Repository:Repository ,私有jwtService:JwtService,私有configService:ConfigService,){}


更多回答

This is not the solution. The error says that it cannot find dependency. As the docs mention this usually means there is a circular file import (not a direct circular dependency) that is causing Typescript to not be able to emit the type metadata for the guard correctly.

这不是解决之道。该错误说明它找不到依赖项。正如文档中提到的,这通常意味着存在循环文件导入(而不是直接循环依赖),导致TypeScrip不能正确地发出警卫的类型元数据。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com