【问题标题】:NestJS / Swagger - Not Getting Complete DescriptionsNestJS / Swagger - 没有得到完整的描述
【发布时间】:2021-01-30 13:13:29
【问题描述】:

我无法让 Swagger 正常工作。我可以获得请求正文的示例,但不能获得响应或 swagger-json。响应显示为{},swagger-json 为:

{
  statusCode: 404,
  message: "Cannot GET /swagger-json",
  error: "Not Found",
}

我的nest-cli.json 文件是:

{
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "deleteOutDir": true,
    "plugins": ["@nestjs/swagger/plugin"]
  }
}

在我的 main.ts 我有:

import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
...
const options = new DocumentBuilder()
    .setTitle('ILuvCoffee')
    .setDescription('Coffee Application')
    .setVersion('1.0')
    .build();

  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api', app, document);

我正在学习 Nest.js 课程,到目前为止,我一直非常忠实地学习。当我遇到这个问题时,我仔细检查了我的代码是否正确,甚至是复制/粘贴。我还仔细检查了我的 DTO 文件是否遵循 *.dto.ts 和我的实体文件 *.entity.ts。但我仍然无法让 Swagger 展示除请求之外的任何内容。想法?谁看到了我看不到的东西?

如果您想深入了解,这里是我的回购:https://github.com/jstrother/iluvcoffee

谢谢!

【问题讨论】:

    标签: swagger nestjs


    【解决方案1】:

    看起来您没有在控制器中指定实际的响应类型,而是使用<any>,例如:

    @Get(':id')
    findOne(@Param('id') id: string): Promise<any> {
      console.log(id);
      return this.coffeesService.findOne(id);
    }
    

    尝试将这些 anys 更改为实际类型

    @Get(':id')
    findOne(@Param('id') id: string): Promise<Coffee> {
      console.log(id);
      return this.coffeesService.findOne(id);
    }
    

    请注意,您还可以使用 ApiResponse 装饰器来明确定义响应 -> 请查看 official example 了解更多详细信息。

    【讨论】:

    • 谢谢!我也在尝试习惯在 Typescript 中思考,这可能是让我感到困惑的原因。
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多