nestjs - Nest 无法解析 JwtStrategy 的依赖关系
问题描述
我是 NestJs 世界的新手。据我所知,我在 JwtStrategy 中导入了所有需要的东西。我不知道哪里出错了。有人可以帮我吗?
就我提到的文档而言,每当我们想在模块中使用任何实体时,我们都应该在 @Module() 装饰器的导入字段中导入该实体。我做到了。
jwt.strategy.ts
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { UserEntity } from "src/entities/user.entity";
import { AuthPayload } from "src/common/dtos/user.dto";
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserEntity)
private userRepo: Repository<UserEntity>
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.SECRETKEY
});
}
async validate(payload: AuthPayload): Promise<UserEntity> {
const { username } = payload;
const user = this.userRepo.findOne({ where: { username: username } });
if(!user) {
throw new UnauthorizedException();
}
return user;
}
}
auth.module.ts
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserEntity } from 'src/entities/user.entity';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
TypeOrmModule.forFeature([UserEntity]),
JwtModule.register({
secret: process.env.SECRETKEY,
}),
PassportModule.register({
defaultStrategy: 'jwt'
})
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [PassportModule, JwtStrategy]
})
export class AuthModule {}
用户实体.ts
import { Entity, Column, OneToMany, JoinTable, BeforeInsert } from "typeorm";
import { AbstractEntity } from "./abstract-entity.abstract";
import { IsEmail } from "class-validator";
import { Exclude, classToPlain } from "class-transformer";
import * as bcrypt from "bcryptjs";
import { CategoryEntity } from "./category.entity";
import { ArticleEntity } from "./article.entity";
@Entity('User')
export class UserEntity extends AbstractEntity {
@Column({
type: "varchar",
length: 80
})
fullName: string;
@Column({
type: "varchar",
unique: true
})
@IsEmail()
email: string;
@Column({
type: "varchar",
unique: true
})
username: string;
@Column({
type: "varchar"
})
@Exclude()
password: string;
@Column({
default: null,
nullable: true
})
avatar: string | null;
@Column({
type: "varchar",
unique: true
})
phoneNumber: string;
@Column({
type: "boolean",
default: false
})
isAdmin: boolean;
@Column({
type: "boolean",
default: false
})
isStaff: boolean;
@Column({
type: "boolean",
default: false
})
isEmailVerified: boolean;
@OneToMany(type => CategoryEntity, category => category.createdBy)
@JoinTable()
categories: CategoryEntity[];
@OneToMany(type => ArticleEntity, article => article.createdBy)
@JoinTable()
articles: ArticleEntity[];
@BeforeInsert()
async hashPassword() {
this.password = await bcrypt.hash(this.password, 10);
}
async comparePassword(attempt: string): Promise<boolean> {
return await bcrypt.compare(attempt, this.password);
}
toJSON(): any {
return classToPlain(this);
}
}
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from "@nestjs/typeorm";
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import {
DatabaseConnectionService
} from "./utils/database-connection.service";
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { ArticlesModule } from './articles/articles.module';
import { HttpExceptionFilter } from './common/exception-filters/http-exception.filter';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { CategoryModule } from './category/category.module';
@Module({
imports: [
TypeOrmModule.forRootAsync({
useClass: DatabaseConnectionService
}),
AuthModule,
UsersModule,
ArticlesModule,
CategoryModule,
],
controllers: [AppController],
providers: [
// {
// provide: APP_INTERCEPTOR,
// useClass: ResponseInterceptor
// },
{
provide: APP_FILTER,
useClass: HttpExceptionFilter
},
AppService
],
})
export class AppModule {}
数据库连接.service.ts
import { Injectable } from "@nestjs/common";
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { truncate } from "fs";
@Injectable()
export class DatabaseConnectionService implements TypeOrmOptionsFactory {
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: "mysql",
host: process.env.HOST,
port: parseInt(process.env.PORT),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DATABASE,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
dropSchema: true,
autoLoadEntities: true,
logger: "simple-console"
};
}
}
解决方案
根据您的错误,您JwtStrategy
在imports
阵列中的某个位置。如果你需要,JwtStrategy
你应该导入AuthModule
,因为提供者应该只在providers
数组中,而不应该在imports
.
推荐阅读
- django - self.request.user 在 Django REST 框架中不起作用
- sql - 在 BIRT 中绘制线性回归线
- mysql - MySQL 查询以检索另一个表中的最后一个条目
- kotlin - 如何在 kotlin 中将扩展运算符与 ArrayList 一起使用?
- statistics - 在双边检验中比较显着性水平与 p 值
- laravel - Vue Props 数据数轮
- python - python中使用n输入的递归函数
- php - Laravel multiauth Gate 不适用于管理表
- azure-databricks - 重命名文件(附加时间戳)并将其移动到 ADLS Gen2(Databricks)上的不同文件夹
- python-3.x - 如何获取我在 sweetify 输入字段中输入的值?