@nestjs/swagger启动报错:TypeError: shared_utils_1.validatePath is not a function
问题背景
使用@nestjs/swagger与swagger-ui-express搭建项目后,每次启动应用都会抛出TypeError: shared_utils_1.validatePath is not a function错误,同时提示存在未处理的Promise拒绝。
配置代码
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); const config = new DocumentBuilder().setTitle("DNXT API") .setDescription("The DNXT api is De generation next api") .setVersion("1.0.0").build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup("/", app, document); await app.listen(3000); } bootstrap();
错误信息
(node:1612) UnhandledPromiseRejectionWarning: TypeError: shared_utils_1.validatePath is not a function at SwaggerExplorer.validateRoutePath (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-explorer.js:135:61) at SwaggerExplorer.generateDenormalizedDocument (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-explorer.js:53:25) at SwaggerExplorer.exploreController (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-explorer.js:47:21) at C:\Users\HP\Desktop\DNXT\nest-ncc\node_modules\@nestjs\swagger\dist\swagger- scanner.js:48:84 at Array.map (<anonymous>) at SwaggerScanner.scanModuleRoutes (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-scanner.js:48:56) at C:\Users\HP\Desktop\DNXT\nest-ncc\node_modules\@nestjs\swagger\dist\swagger- scanner.js:39:25 at Array.map (<anonymous>) at SwaggerScanner.scanApplication (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-scanner.js:25:43) at Function.createDocument (C:\Users\HP\Desktop\DNXT\nest- ncc\node_modules\@nestjs\swagger\dist\swagger-module.js:19:41) (node:1612) UnhandledPromiseRejectionWarning:
解决方案
1. 修复核心版本不匹配问题
该错误本质是@nestjs/swagger版本与@nestjs/core、@nestjs/common等NestJS核心包版本不一致,导致内部依赖的工具方法缺失。
- 打开项目根目录的
package.json,检查@nestjs/swagger、@nestjs/core、@nestjs/common的版本号,确保三者版本完全一致。 - 删除
node_modules文件夹和package-lock.json(或yarn.lock)文件。 - 重新执行
npm install或yarn install安装依赖。
2. 处理未捕获Promise拒绝
修改启动函数,添加错误捕获逻辑,避免控制台警告:
async function bootstrap() { try { const app = await NestFactory.create(AppModule); const config = new DocumentBuilder() .setTitle("DNXT API") .setDescription("The DNXT api is De generation next api") .setVersion("1.0.0") .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup("/", app, document); await app.listen(3000); } catch (error) { console.error('启动失败:', error); process.exit(1); } } bootstrap();
内容的提问来源于stack exchange,提问作者Fjay
相关产品推荐
相关产品推荐

