簡體   English   中英

如何在 NestJS 中處理來自 post 請求正文的意外數據

[英]How to handle unexpected data from the post request body in NestJS

在 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 ,您可以將所有屬性傳遞給類驗證器選項支持的驗證 pipe。

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

  forbidUnknownValues?: boolean;
  stopAtFirstError?: boolean;
}

如果您不僅想剝離值,而且在傳遞意外值時拋出錯誤,您可以使用forbidUnknownValues: true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM