You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS Swagger v6.3.0发送字符串而非数组问题求助

解决@nestjs/swagger 6.3.0中字符串数组ApiProperty定义导致Swagger UI发送非数组的问题

问题重现

使用@nestjs/swagger 6.3.0定义接收字符串数组的API字段时,以下两种写法均无法让Swagger UI正确发送数组参数,而是发送字符串:

@ApiProperty({ type: "array", items: { type: "string" }, })  
clients: string[]
@ApiProperty({ isArray: true, items: { type: "string" }, })  
clients: string[]

解决方案

方案1:结合isArray与明确的元素类型

在@nestjs/swagger 6.x版本中,正确定义字符串数组的方式是指定type: String并开启isArray: true,添加example可以帮助Swagger UI渲染出符合预期的数组输入框:

import { ApiProperty } from '@nestjs/swagger';

export class ClientIdsDto {
  @ApiProperty({
    isArray: true,
    type: String,
    example: ['client_001', 'client_002'],
    description: '客户端ID列表'
  })
  clients: string[];
}

方案2:直接使用数组形式的type参数

也可以将type设置为[String],这种写法同样能被Swagger正确识别为数组类型:

@ApiProperty({
  type: [String],
  example: ['client_001', 'client_002']
})
clients: string[];

针对查询参数的特殊处理

如果该数组是作为URL查询参数而非请求体字段,需要使用@ApiQuery装饰器并配置参数样式,确保Swagger UI生成正确的数组输入:

import { Controller, Get, Query } from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';

@Controller('clients')
export class ClientsController {
  @Get()
  @ApiQuery({
    name: 'clients',
    isArray: true,
    type: String,
    style: 'form',
    explode: true
  })
  getClients(@Query('clients') clients: string[]) {
    return { receivedClients: clients };
  }
}

验证

修改完成后重启服务,打开Swagger UI即可看到对应的数组输入框,输入多个值后发送请求,服务器将接收到正确的字符串数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:10:15