typescript - 创建 JWT 令牌时找不到 404 错误
问题描述
您好,我得到了一个 404 未找到的错误,如下面的屏幕截图所示。我使用正确的路径,但仍然出现错误
这是用户服务的代码:
constructor(@Inject('UserModelToken') private readonly userModel: Model<User>) { }
async findAll(): Promise<User[]> {
return await this.userModel.find().exec();
}
async findOne(payload: JwtPayload): Promise<User[]> {
return await this.userModel.findOne({ username: payload.username }).exec();
}
async create(createUserDto: CreateUserDto): Promise<User> {
//createUserDto.password = await this.getHash(createUserDto.password);
const createdUser = new this.userModel(createUserDto);
return await createdUser.save();
}
}
这是AuthService的代码:
constructor(private readonly jwtService: JwtService, private readonly usersService: UsersService) { }
async createToken(user: JwtPayload) {
// const user: JwtPayload = { email: 'test@email.com' };
const accessToken = this.jwtService.sign(user);
return {
expiresIn: 3600,
accessToken,
};
}
async validateUser(payload: JwtPayload): Promise<any> {
// Validate if token passed along with HTTP request
// is associated with any registered account in the database
return await this.usersService.findOne(payload);
}
}
这是AuthController的代码:
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService, private readonly usersService: UsersService) { }
@Post('login')
async login(@Body() payload: JwtPayload) {
const user = await this.usersService.findOne(payload);
if (user) {
//if (await this.usersService.compareHash(payload.password, user['password'])) {
return await this.authService.createToken(payload);
}
else {
throw new HttpException({
status: HttpStatus.UNAUTHORIZED,
error: 'Wrong username or password',
}, HttpStatus.UNAUTHORIZED);
}
}
这是DTO的代码:
import {IsString, IsInt,IsEmail,IsNotEmpty, IsNumberString, IsIn,IsHash} from 'class-validator'
export class CreateUserDto{
@IsEmail()
username:string
@IsNotEmpty()
password:string
}
解决方案
在您的 DTO 中,您使用String
而不是string
密码类型。这可能会弄乱您的输入类型。