shu*_*hun 10 nestjs nestjs-passport nestjs-config nestjs-jwt
我有一个关于设置环境变量的问题。
在官方文档中,它说在这种情况下使用ConfigModule,但我的情况是一个例外情况。
因为我想在构造函数的 super() 中使用它。
我的代码如下。
这种情况有什么解决办法吗?
如果您需要更多信息,请告诉我。
谢谢大家的支持!!
// jwt.strategy.ts
import { UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { JwtPayload } from './jwt-payload.interface';
import { UserRepository } from './user.repository';
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get('JWT_TOKEN'),
});
}
async validate(payload: JwtPayload) {
const { username } = payload;
const user = await this.userRepository.findOne({ username });
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我还想指出,由于您没有在configService任何地方使用,但在super()调用中使用private它前面的关键字是多余的
你可以尝试使用this.configService.get('JWT_TOKEN'),但它只会对你大喊你还没有调用 super
删除 private 关键字将简单地避免将 theconfigService作为类变量,并将其视为传递给它的某些选项
| 归档时间: |
|
| 查看次数: |
4763 次 |
| 最近记录: |