问题
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