[英]Swagger UI always shows up in NestJS
I am currently learning my way around in NestJS.我目前正在学习 NestJS 中的方法。 Now I am experimenting with the Swagger feature.
现在我正在试验 Swagger 功能。 I followed the explanations on the NestJS site and I am getting a nice Swagger page displayed.
我按照 NestJS 站点上的说明进行操作,并且显示了一个不错的 Swagger 页面。 However, now I am no longer able to use my controller pathes.
但是,现在我无法再使用我的控制器路径。
Example:例子:
I have a path /api/users
that will return a list of user records.我有一个路径
/api/users
将返回用户记录列表。 After adding the Swagger feature I get the Swagger UI on /api
.添加 Swagger 功能后,我在
/api
上获得了 Swagger UI。 When I try to request /api/users
I also get the swagger UI, this time empty.当我尝试请求
/api/users
我也得到了 swagger UI,这次是空的。
When I click the "Try it out" button for the "user" API /users
instead of /api/users
will be executed, of course with a 404 response.当我单击“用户”API 的“试用”按钮时,
/users
而不是/api/users
将被执行,当然会有 404 响应。
What am I doing wrong?我究竟做错了什么? Please help.
请帮忙。
I'm assuming you have set the global prefix of your app to /api
.我假设您已将应用程序的全局前缀设置为
/api
。 Then you also have to set the base path for swagger accordingly.然后,您还必须相应地设置 swagger 的基本路径。 Also, you should mount your swagger docs to an unused path:
此外,您应该将 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);
// ^^^^^^
I was able to achieve this by below code:我能够通过以下代码实现这一点:
app.setGlobalPrefix("api");
setupSwagger(app);
app.setGlobalPrefix("");
setupSwagger definition: setupSwagger 定义:
export const setupSwagger = (app: INestApplication) => {
const options = new DocumentBuilder()
.setTitle(SWAGGER_API_NAME)
.setDescription(SWAGGER_API_DESCRIPTION)
.setVersion(SWAGGER_API_CURRENT_VERSION)
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup(SWAGGER_API_ROOT, app, document);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.