如何在NestJS中处理来自post请求主体的意外数据



在NestJS官方验证教程中。我们可以处理客户端发布请求中的错误数据类型。

// dtos/CreateUserDto.ts
import { IsEmail, IsNotEmpty } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsNotEmpty()
password: string;
}
// controllers/user.controller.ts
@Post()
async createUser(@Body() body: CreateUserDto) {
return body;
}

当我创建一个类似的帖子请求时

curl -X POST 'http://domain/user' -d '{"email": "john", "password": "changeme"}' -H "Content-Type: application/json"

我将得到预期的错误返回。

{
"statusCode": 400,
"message": [
"email must be an email"
],
"error": "Bad Request"
}

我担心的是一种情况,发布带有意外数据的请求

curl -X POST 'http://domain/user' -d '{"email": "john@example.com", "password": "changeme", "foo": "bar"}' -H "Content-Type: application/json"

我会得到回报的。

{
"email": "john@example.com",
"password": "changeme",
"foo": "bar"
}

我想密钥foo会被删除或返回系统错误,但它不会这样做。

处理这种情况的最佳方法是什么?

由于NestJS使用class-validator,您可以将类验证器选项支持的所有属性传递到验证管道。

ValidatorOptions {
skipMissingProperties?: boolean;
whitelist?: boolean;
forbidNonWhitelisted?: boolean;
groups?: string[];
dismissDefaultMessages?: boolean;
validationError?: {
target?: boolean;
value?: boolean;
};
forbidUnknownValues?: boolean;
stopAtFirstError?: boolean;
}

如果您不仅希望剥离值,而且希望在传递意外值时抛出错误,则可以使用forbidUnknownValues: true

最新更新