尝试通过在控制器路由调用 @requestBody 注解来通过 DTO 验证请求。
控制器方法 -
@httpPost('/login')
public async login(@request() req: Request, @response() res: Response, @requestBody() body: LoginDto): Promise<any> {
console.log("🚀 ~ file: auth.controller.ts:20 ~ AuthController ~ login ~ body:", body)
return res.status(200).json(body);
}
DTO-
export interface LoginDto {
email: string;
password: string;
}
请求正文 -
{
email: 'hellowor[email protected]',
password: '1234',
confirm_password: '1234'
}
预期输出 -
~ file: auth.controller.ts:20 ~ AuthController ~ login ~ body: {
email: '[email protected]',
password: '1234'
}
实际产量-
~ file: auth.controller.ts:20 ~ AuthController ~ login ~ body: {
email: 'hellowor[email protected]',
password: '1234',
confirm_password: '1234'
}
DTO 没有按预期工作。不确定出了什么问题。如果有人以前经历过这种情况并有解决方案,那么这将会有所帮助。谢谢!
如果您首先使用
inversify-express-utils
,您需要在应用程序的起点解析正文
var container = new Container();
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
app.use(express.json());
});