NestJS认证接口出现500内部服务器错误排查求助
问题解决:NestJS登录接口500错误("You must provide selection conditions...")
错误根源
你调用TypeORM的findOne方法时传入了单个字符串(email值),但该方法默认会把单个值当作主键查询条件。而你的UserEntity主键是id而非email,导致查询条件无效,触发了这个错误。
修复方案
方案1:调整控制器的调用参数
在登录接口中,调用findOneBy时传入查询条件对象,而非直接传email字符串:
@Post('login') async login( @Body() body: LoginDto, @Res({passthrough: true}) response: Response ) { // 修改为传入条件对象 { email: body.email } const user = await this.authService.findOneBy({ email: body.email }); if(!user){ throw new BadRequestException("Email does not exist"); } if(!await bcrypt.compare(body.password, user.password)){ throw new BadRequestException("Password does not match"); } const jwt = await this.jwtService.signAsync({id: user.id}); response.cookie('jwt', jwt, {httpOnly: true}); return { user }; }
方案2:修改AuthService的findOneBy方法
如果希望findOneBy专门用于按email查询,直接在方法内部包装查询条件:
@Injectable() export class AuthService { constructor(@InjectRepository(UserEntity) private readonly userRepository: Repository<UserEntity>){} async findOneBy(email: string): Promise<User> { // 包装成TypeORM要求的查询格式 return await this.userRepository.findOne({ where: { email } }); } }
注意:若你的TypeORM版本是0.3.x及以上,
findOne必须传入{ where: ... }格式的参数;0.2.x版本可直接传条件对象。请根据实际版本调整代码。
额外检查
确保NestJS已正确配置ValidationPipe,保证LoginDto的校验逻辑生效,避免传入空email值导致查询条件仍然无效。
内容的提问来源于stack exchange,提问作者Nicolas Bernal
相关产品推荐
相关产品推荐

