You need to enable JavaScript to run this app. Nest.js中如何在请求到达Guard前完成输入验证与sanitise处理
优惠活动
大模型
产品
解决方案
定价
更多

Nest.js中如何在请求到达Guard前完成输入验证与sanitise处理

Nest.js 注册请求参数预处理方案

首先明确Nest.js默认的请求生命周期执行顺序:

  • 全局/模块/路由级中间件
  • 全局/控制器/路由级守卫
  • 拦截器前置逻辑
  • 全局/控制器/路由/参数级管道
  • 路由处理函数

默认自带的ValidationPipe执行顺序在守卫之后,所以守卫默认只能拿到未校验的原始入参,想要在守卫执行前完成参数验证、清理,有两种可落地的方案:

方案1:在中间件层做参数校验(最贴合你的需求)

中间件执行顺序早于所有守卫,直接在这里完成入参的格式校验、非法字符清理、类型转换即可,你可以直接复用class-validator+class-transformer的能力:

  1. 首先定义注册参数DTO
import { IsString, IsEmail, Length, IsNotEmpty } from 'class-validator';

export class RegisterDto {
  @IsNotEmpty()
  @IsString()
  @Length(2, 20)
  name: string;

  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  @Length(6, 32)
  password: string;
}
  1. 实现验证中间件
import { Injectable, NestMiddleware, BadRequestException } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { Request, Response, NextFunction } from 'express';
import { RegisterDto } from './dto/register.dto';

@Injectable()
export class RegisterValidationMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    // 仅匹配注册路由执行校验,其他路由可按需扩展规则
    if (req.path === '/auth/register' && req.method === 'POST') {
      const validatedDto = plainToInstance(RegisterDto, req.body);
      const errors = await validate(validatedDto);
      if (errors.length > 0) {
        throw new BadRequestException('参数格式非法', errors.toString());
      }
      // 把清理后的合法DTO挂载到请求对象,后续守卫和路由可直接使用
      req.body = validatedDto;
    }
    next();
  }
}
  1. 模块中注册中间件
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { RegisterValidationMiddleware } from './register-validation.middleware';

@Module({...})
export class AuthModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(RegisterValidationMiddleware).forRoutes('auth/register');
  }
}

方案2:调整校验逻辑分层(复用Nest原生管道能力)

如果你不想额外维护中间件逻辑,也可以调整校验职责划分:保留Nest全局ValidationPipe做参数清理验证,把「用户是否存在」的数据库校验逻辑从守卫移到管道之后的自定义管道、拦截器或者路由前置逻辑中,这个方案更贴合Nest的职责分层设计:守卫负责权限、身份类校验,参数合法性校验归属管道层。


内容的提问来源于stack exchange,提问作者Sarath Radhakrishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 01:57:00