如何在NestJS/Swagger中禁用或隐藏Petstore页面?
解决NestJS/Swagger默认Petstore页面问题
以下几种方法可以实现禁用、隐藏默认的Petstore页面,或返回自定义的"api not found"内容:
1. 完全不挂载Swagger UI(推荐不需要UI时使用)
如果只需要生成OpenAPI的JSON/YAML文档,不需要Swagger UI界面,直接跳过SwaggerModule.setup()方法,仅注册文档接口即可。此时访问/api/index.html会返回404。
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 生成OpenAPI文档 const config = new DocumentBuilder() .setTitle('你的API') .setDescription('API描述') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // 仅暴露JSON格式的文档接口,不挂载Swagger UI app.use('/api/docs', (req, res) => res.json(document)); await app.listen(3000); } bootstrap();
2. 修改Swagger UI的挂载路径
将Swagger UI挂载到非/api的路径下,比如/api/docs,这样原路径/api/index.html就会返回404。
async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('你的API') .setDescription('API描述') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // 将Swagger UI挂载到/api/docs路径 SwaggerModule.setup('api/docs', app, document); await app.listen(3000); } bootstrap();
3. 拦截/api/index.html请求返回自定义内容
如果需要保留/api路径下的Swagger UI,但要拦截/api/index.html请求,可在挂载Swagger UI之前注册一个路由处理该请求,返回404或自定义内容。
async function bootstrap() { const app = await NestFactory.create(AppModule); // 先注册拦截路由,必须在SwaggerModule.setup()之前 app.get('/api/index.html', (req, res) => { res.status(404).send('api not found'); }); const config = new DocumentBuilder() .setTitle('你的API') .setDescription('API描述') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // 正常挂载Swagger UI到/api路径 SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap();
4. 替换Swagger UI的默认内容
通过SwaggerUiOptions的customHtml选项,直接替换默认的Petstore页面内容为自定义的"api not found"。
import { SwaggerUiOptions } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle('你的API') .setDescription('API描述') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // 自定义UI内容 const uiOptions: SwaggerUiOptions = { customHtml: ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>API Not Found</title> </head> <body> <h1 style="text-align:center; margin-top:50px;">api not found</h1> </body> </html> `, }; SwaggerModule.setup('api', app, document, uiOptions); await app.listen(3000); } bootstrap();
内容的提问来源于stack exchange,提问作者Anas Khan
相关产品推荐
相关产品推荐

