Nest.js + Swagger 中未显示请求正文

Request body not showing in Nest.js + Swagger

我的控制器代码是这样的。

@Controller('customer')
export class CustomerController{

    constructor(private readonly customerService: CustomerService){}

    @Post('lookup')
    async someMethod(@Body() body:any){

        console.log("BEGIN -- CustomerController.someMethod");

我希望在 Swagger 中看到一个可以输入一些文本作为请求正文的地方,但我却看到了这个

所以听起来这里发生了一些事情。 Swagger UI 是发送请求的辅助工具,但要做到这一点,它需要知道请求主体的形状。 any 不够好。如果您正在寻找一种可以发送任何东西的工具,那么 curl 或 postman 是您最好的选择(至少是免费的)。

Nest 有一个 Swagger plugin 可以读取您的 Typescript 代码并相应地修饰您的类型和方法,但您必须选择启用它。否则,您需要使用 @nestjs/swagger 包中的装饰器来告诉 Swagger 方法中和方法外预期的类型。

只要对应 @Body() 的类型有 swagger 装饰器 你启用 swagger 插件 有一个valid class,swagger UI 应该会按预期显示,但是使用上述内容并使用类型 any 对您没有任何好处。

我的端点接受未知的 key/value 数据,我遇到了同样的问题(我试过 any, unknown, Record, object, {} ).终于 @Body() data: Map<string, any> 为我工作了。

添加@ApiProperty()

export class User{

 @ApiProperty()
  name:string
 
}

试试这样:

@ApiBody({description: "body:any someMethod"})
@Post('lookup')
async someMethod(@Body() body:any){
console.log("BEGIN -- CustomerController.someMethod");
}

Swagger 无法解释您的代码。您的代码不是问题。如果您的目标是测试 API 供 UI 团队使用,而不是全面的 swagger 文档,那么我发现使用 Postman 最简单。 尝试使用 Postman 访问您的 API。