在邮递员的正文中传递电子邮件和密码时,我收到验证管道错误 [英] I got a validation pipe's error when am passing email and password in the body of the postman

查看:51
本文介绍了在邮递员的正文中传递电子邮件和密码时,我收到验证管道错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误截图如下:

这是DTO的代码:

import {IsString, IsInt,IsEmail,IsNotEmpty, IsNumberString, IsIn} from 'class-validator'

export class logindto{
    @IsEmail()
    username:String

    @IsNotEmpty()
    password:String
}

这是控制器的代码:

@Post('login')
log(@Body('username')username:logindto,@Body('password')password:logindto):any{
    return this.crudservice.loginsys(username,password)
}

这里是服务代码:

export class CrudService {
    constructor(@InjectModel('student') private readonly student:Model<studentmodel>){} 

    async loginsys(username,password):Promise<any>{
            const cred=this.student.findOne({username:username,password:password})
            return cred
    }
}

这是模型的代码:

import * as mongoose from 'mongoose'


export const studentschema=new mongoose.Schema({
    name:{type:String,required:true},
    std:{type:Number},
    rollno:{type:Number},
    section:{type:String},
    username:{type:String},
    password:{type:String}
});

export interface studentmodel  extends mongoose.Document{
   readonly name:String,
   readonly std:Number,
   readonly rollno:Number,
   readonly section:string,
   readonly username:string,
   readonly password:string
}

我已经通过了 form-data:application/x-www-url-form-encoded 或 application/json 的标头.但仍然出现相同的错误

I already passed header of form-data:application/x-www-url-form-encoded or application/json.But still got the same error

推荐答案

通过在 @Body() 装饰器中包含字符串,您告诉 nest 找到 'username'<req.body 的/code> 属性,但你也说 req.body.username 应该是 logindto,所以 class-validator期望找到 req.body.username.usernamereq.body.username.password 以及 req.body.password.usernamereq.body.password.password.要解决此问题,请从 @Body() 装饰器中删除字符串.如果您需要分别获取用户名和密码,您可以使用对象解构,但我建议在签名的之外,在方法的主体中进行.

By having strings inside of your @Body() decorators, you are telling nest to find the 'username' property of req.body, but you are also saying that req.body.username should be a logindto, so class-validator is expecting to find req.body.username.username and req.body.username.password along with req.body.password.username and req.body.password.password. To fix this, remove the strings from the @Body() decorator. If you need to get the username and password separately, you can use object deconstruction, but I would suggest doing that outside of the signature, in the body of the method.

@Post('login')
log(@Body()login:logindto,):any{
    const { username, password } = login; // <-- deconstructing the incoming payload
    return this.crudservice.loginsys(username,password)
}

这篇关于在邮递员的正文中传递电子邮件和密码时,我收到验证管道错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆