首页 > 解决方案 > Swagger UI 总是出现在 NestJS 中

问题描述

我目前正在学习 NestJS。现在我正在尝试使用 Swagger 功能。我按照 NestJS 网站上的说明进行操作,并显示了一个不错的 Swagger 页面。但是,现在我不再能够使用我的控制器路径。

示例:
我有一个/api/users将返回用户记录列表的路径。添加 Swagger 功能后,我打开了 Swagger UI /api。当我尝试请求时,/api/users我也得到了招摇的 UI,这次是空的。
当我单击“用户”API 的“试用”按钮/users而不是/api/users将执行时,当然会出现 404 响应。

我究竟做错了什么?请帮忙。

标签: javascriptnode.jstypescriptswaggernestjs

解决方案


我假设您已将应用程序的全局前缀设置为/api. 然后,您还必须相应地设置 swagger 的基本路径。此外,您应该将 swagger 文档安装到未使用的路径:

// Set the global prefix for all controllers to /api
app.setGlobalPrefix('api');

const document = SwaggerModule.createDocument(
  app,
  new DocumentBuilder()
    // Set the base path for swagger accordingly
    .setBasePath('api')
    .build(),
);

// Choose an unused path to mount your swagger module
SwaggerModule.setup('docs', app, document);
//                  ^^^^^^

推荐阅读