I got a validation pipe's error when am passing email and password in the body of the postman

守給你的承諾、 提交于 2021-01-29 10:19:44

问题


Here is the screenshot of error:

Here is the code of DTO:

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

export class logindto{
    @IsEmail()
    username:String

    @IsNotEmpty()
    password:String
}

Here is the code of controller:

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

Here is the code of services:

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
    }
}

Here is the code of model:

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
}

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


回答1:


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)
}


来源:https://stackoverflow.com/questions/61255126/i-got-a-validation-pipes-error-when-am-passing-email-and-password-in-the-body-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!