如何在 NEST JS 中启用 DTO 验证器

Dan*_*TIZ 7 node.js typescript nestjs

我是 NEST JS 的新手,现在我尝试在 DTO 中包含一些验证器,如下所示:


// /blog-backend/src/blog/dto/create-post.dto.ts
import { IsEmail, IsNotEmpty, IsDefined } from 'class-validator';
export class CreatePostDTO {
  @IsDefined()
  @IsNotEmpty()
  title: string;
  @IsDefined()
  @IsNotEmpty()
  description: string;
  @IsDefined()
  @IsNotEmpty()
  body: string;
  @IsEmail()
  @IsNotEmpty()
  author: string;
  @IsDefined()
  @IsNotEmpty()
  datePosted: string;
}

Run Code Online (Sandbox Code Playgroud)

但是当我执行邮政服务时,例如:

{
    "title":"juanita"
}
Run Code Online (Sandbox Code Playgroud)

其回报良好!但是验证器应该显示错误吗?

我的后置控制器

@Post('/post')
  async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
    console.log(createPostDTO)
    const newPost = await this.blogService.addPost(createPostDTO);
    return res.status(HttpStatus.OK).json({
      message: 'Post has been submitted successfully!',
      post: newPost,
    });
  }
Run Code Online (Sandbox Code Playgroud)

我的 main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  await app.listen(5000);
}
bootstrap();

Run Code Online (Sandbox Code Playgroud)

hoa*_*gdv 15

让我们ValidationPipe在应用程序级别进行绑定,从而确保所有端点都受到保护,不会接收到错误的数据。Nestjs文档

为您的应用程序启用ValidationPipe

主要.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common'; // import built-in ValidationPipe

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe()); // enable ValidationPipe`
  await app.listen(5000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)