如何在NestJS Swagger中仅展示指定模块的API接口
解决方案
核心错误原因
你配置SwaggerDocumentOptions的include参数时错误使用箭头函数包裹模块类,NestJS Swagger模块要求include数组中直接传入需要包含的模块类本身,不需要额外函数包裹,这是接口无法被扫描到的核心原因。
同时注意检查模块名拼写:你描述中定义的是DriverModule(司机模块),配置中写的是DriversModule,拼写不一致也会导致扫描失败。
修复后的配置
// 提前导入依赖和对应模块 import { SwaggerDocumentOptions } from '@nestjs/swagger'; import { DriverModule } from './driver/driver.module'; // 确保路径、模块名和你项目实际定义一致 const option: SwaggerDocumentOptions = { include: [DriverModule], // 直接传入模块类,移除箭头函数包裹 deepScanRoutes: true } const document = SwaggerModule.createDocument(app, config, option);
补充排查项
如果修改后仍然提示No operations defined in spec!,按以下规则排查:
- 确认
DriverModule已经在AppModule的imports数组中完成注册 - 确认
DriverModule下的控制器都添加了@Controller()装饰器,接口方法都添加了@Get/@Post等HTTP请求装饰器 - 确认
@nestjs/swagger包的版本和@nestjs/core、@nestjs/common包大版本一致,跨版本使用会导致扫描异常
内容的提问来源于stack exchange,提问作者Mritunjay Upadhyay
相关产品推荐
相关产品推荐

