我是 Nest.js 的初学者,我发现它非常好。我阅读了官方文档并了解了 DTO。当我的 body 是这样的时候:
{
"username" : "username",
"password" : "password"
}
然后我可以像这样简单地创建 user.dto.ts
:
import { IsNotEmpty } from 'class-validator';
export class UserDTO {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
然后我像这样在我的 Controller 中使用它。
@Post('login')
@UsePipes(new ValidationPipe())
login(@Body() data: UserDTO) {
return this.userService.login(data);
}
但我的问题是,如果我的 body 是这样的怎么办。
{
"data": {
"username": "username",
"password": "password",
}
}
那么我需要对我的 ```user.dto.ts`` 文件进行哪些修改才能使其正常工作?谢谢
最佳答案
答案是:您不需要修改您的DTO
。
@Body()
装饰器还接受一个可选参数:@Body(path?: string)
。
这里的关键是理解@Body()
做了什么。 @Body()
没有任何参数将返回 req.body
对象。 @Body('path')
将返回 req.body.path
(或 req.body['path']
)。有了这些知识,你可以在 @Body('data')
中传递 'data'
它会返回 req.body.data
这将是你的 DTO
.
@Post('login')
@UsePipes(new ValidationPipe())
login(@Body('data') data: UserDTO) {
// data will be your req.body.data which is your UserDTO
return this.userService.login(data);
}
关于javascript - 如何在 Nest.js 中为 @Body 构造 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473153/