NestJS中whitelist设为true时如何在POST请求传递字典?
解决NestJS whitelist=true时接收字符串键映射对象为空的问题
问题核心是:当whitelist设为true时,NestJS的class-transformer默认无法识别索引签名/Record类型的属性(比如Record<string, CreateBlogDto>),会将这类属性视为未知属性过滤掉,导致后端收到空请求体。
解决方案
1. 修改DTO,添加类型转换装饰器
给blogTranslations属性添加@Type()装饰器,明确告知class-transformer如何转换嵌套的CreateBlogDto对象,确保该属性不会被whitelist过滤:
import { Type } from 'class-transformer'; import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { CreateBlogDto } from './create-blog.dto'; @ApiExtraModels(CreateBlogDto) export class CreateBlogTranslationsDto { @ApiProperty({ type: 'object', additionalProperties: { $ref: getSchemaPath(CreateBlogDto) }, }) // 关键:指定每个值的转换类型为CreateBlogDto @Type(() => CreateBlogDto) blogTranslations: Record<string, CreateBlogDto>; }
2. 确保ValidationPipe开启transform选项
在main.ts的全局管道配置中,必须开启transform: true,否则class-transformer无法执行对象转换:
import { ValidationPipe } from '@nestjs/common'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true, // 必须开启,让class-transformer生效 })); await app.listen(3000); } bootstrap();
3. 可选:跳过验证(优先保证数据传递)
如果不需要对blogTranslations做验证,仅需确保数据能传递到后端,可以额外添加@Allow()装饰器(从class-validator导入),明确允许该属性通过whitelist:
import { Type } from 'class-transformer'; import { Allow } from 'class-validator'; import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { CreateBlogDto } from './create-blog.dto'; @ApiExtraModels(CreateBlogDto) export class CreateBlogTranslationsDto { @ApiProperty({ type: 'object', additionalProperties: { $ref: getSchemaPath(CreateBlogDto) }, }) @Allow() // 允许属性通过whitelist,忽略验证规则 @Type(() => CreateBlogDto) blogTranslations: Record<string, CreateBlogDto>; }
验证效果
修改后,发送你期望的请求体格式:
{ "blogTranslations": { "en": { "title": "English title", "description": "English description" }, "es": { "title": "Spanish title", "description": "spanish description" } } }
后端就能正常接收完整的请求体,同时whitelist: true的配置依然生效。
内容的提问来源于stack exchange,提问作者Mtey
相关产品推荐
相关产品推荐

