gpt4 book ai didi

node.js - Nest 无法解析 AuthGuard(Guard 装饰器)的依赖关系

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:33 24 4
gpt4 key购买 nike

我有一个 AuthGuard,负责检查 Controller 中的 JWT token 。我想在 Controller 中使用这个 Guard 来检查身份验证。我有这个错误:

Nest can't resolve dependencies of the AuthGuard (?, +). Please make sure that the argument at index [0] is available in the current context.

TestController.ts

import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
UseInterceptors,
UseGuards,
} from "@nestjs/common";
import { TestService } from "Services/TestService";
import { CreateTestDto } from "Dtos/CreateTestDto";
import { ApiConsumes, ApiProduces } from "@nestjs/swagger";
import { AuthGuard } from "Guards/AuthGuard";

@Controller("/tests")
@UseGuards(AuthGuard)
export class TestController {
constructor(
private readonly testService: TestService,
) {}

@Post("/create")
@HttpCode(HttpStatus.OK)
@ApiConsumes("application/json")
@ApiProduces("application/json")
async create(@Body() createTestDto: CreateTestDto): Promise<void> {
// this.testService.blabla();
}
}

AuthGuard.ts

import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { AuthService } from "Services/AuthService";
import { UserService } from "Services/UserService";

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly authService: AuthService,
private readonly userService: UserService,
) {}

async canActivate(dataOrRequest, context: ExecutionContext): Promise<boolean> {
try {
// code is here
return true;
} catch (e) {
return false;
}
}
}

最佳答案

AuthService(无法解析的依赖项)必须在包含使用防护的 Controller 的范围内可用。

这是什么意思?

在加载 Controller 的模块的 providers 中包含 AuthService

例如

@Module({
controllers: [TestController],
providers: [AuthService, TestService, UserService],
})
export class YourModule {}

编辑 - 忘记提及另一种干净的方式(也许更干净,取决于上下文)包括导入提供(导出)服务的模块

例如

@Module({
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}

@Module({
imports: [AuthModule],
controllers: [TestController],
providers: [TestService, UserService],
})
export class YourModule {}

关于node.js - Nest 无法解析 AuthGuard(Guard 装饰器)的依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51418222/

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