如何在NestJS的Swagger文档中添加服务器示例选项?
在NestJS Swagger中添加多服务器示例选项
你提到的addServer()方法其实支持多次调用,每调用一次就会添加一个服务器选项,最终在Swagger UI里会呈现出下拉选择器(和你想要的示例效果一致)。具体实现步骤如下:
- 在项目的
main.ts中,通过DocumentBuilder构建文档配置时,多次调用addServer()方法,传入不同的服务器地址和描述:
import { NestFactory } from '@nestjs/core'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('你的API标题') .setDescription('API描述') .setVersion('1.0') // 添加本地开发环境服务器示例 .addServer('http://localhost:3000', '本地开发环境') // 添加预发布环境服务器示例 .addServer('https://staging.yourdomain.com', '预发布环境') // 添加生产环境服务器示例 .addServer('https://prod.yourdomain.com', '生产环境') .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();
- 启动项目后访问Swagger UI(默认路径为
/api),就能看到顶部的服务器下拉选择器,里面包含你配置的所有服务器选项,和目标效果一致。
另外,addServer()还支持传入变量参数,适配带路径变量的服务器地址场景:
.addServer('https://{region}.yourdomain.com', '区域化服务器', { region: { default: 'us-east-1', description: '服务器所在区域' } })
配置后Swagger UI会允许用户选择或输入对应的变量值,满足更复杂的服务器配置需求。
内容的提问来源于stack exchange,提问作者Alana Rodrigues Rocha
相关产品推荐
相关产品推荐

