NestJS项目无法连接数据库求助(含MySQL/MongoDB报错)
排查NestJS数据库连接失败问题
问题现象
- MySQL项目报错:
ERROR [TypeOrmModule] Unable to connect to the database. Retrying (3)... Error: connect ECONNREFUSED 127.0.0.1:3306 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) - 此前正常运行的MongoDB项目也连接失败:
- Angular代理请求
localhost:4200/auth到http://localhost:3000时出现ECONNREFUSED错误 - NetJets提示无法连接数据库
- Angular代理请求
环境:Windows 11、Angular CLI:14.0.6、Node:16.16.0、npm:8.14.0、NestJS:9.0
排查步骤
1. 确认数据库服务状态
- MySQL:按
Win+R输入services.msc打开服务列表,找到MySQL服务,确认状态为「正在运行」。未运行则右键启动;启动失败需查看事件日志排查原因,或检查my.ini配置的端口是否为3306。 - MongoDB:同样在服务列表中确认MongoDB服务运行状态,也可在命令行执行
mongod尝试手动启动,检查配置文件中的端口(默认27017)是否正确。
2. 验证端口连通性
- 用PowerShell测试端口是否可访问:
- MySQL:
Test-NetConnection 127.0.0.1 -Port 3306,查看TcpTestSucceeded是否为True - MongoDB:
Test-NetConnection 127.0.0.1 -Port 27017,同理检查连通性
- MySQL:
- 检查端口占用:命令行执行
netstat -ano | findstr :3306(MySQL)或netstat -ano | findstr :27017(MongoDB),若有非数据库服务占用端口,结束对应进程。
3. 检查NestJS数据库配置
- MySQL(TypeOrm):确认
app.module.ts中的配置参数:
重点核对host、port、账号密码,敏感信息建议用环境变量存储,避免硬编码解析错误。TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: '你的用户名', password: '你的密码', database: '目标库名', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }) - MongoDB(Mongoose):确认Mongoose连接配置:
若开启了认证,需补充账号密码:MongooseModule.forRoot('mongodb://localhost:27017/目标库名')mongodb://用户名:密码@localhost:27017/目标库名
4. 确认NestJS服务与Angular代理状态
- 启动NestJS项目时,查看控制台是否输出
Nest application successfully started,若无则说明服务因数据库连接失败未启动,优先解决数据库问题。 - 检查Angular的
proxy.conf.json配置,确保目标地址与NestJS服务端口一致:{ "/auth/*": { "target": "http://localhost:3000", "secure": false, "changeOrigin": true } }
5. 核对依赖版本兼容性
- TypeOrm与NestJS:NestJS 9.0适配TypeOrm 0.3.x系列,查看
package.json版本:
版本不匹配则执行卸载重装:"@nestjs/typeorm": "^9.0.1", "typeorm": "^0.3.17"npm uninstall @nestjs/typeorm typeorm npm install @nestjs/typeorm@^9.0 typeorm@^0.3 - Mongoose与NestJS:NestJS 9适配Mongoose 6.x/7.x系列,核对
package.json:"@nestjs/mongoose": "^9.2.2", "mongoose": "^7.6.3"
6. 排查防火墙拦截
- 临时关闭Windows Defender防火墙,测试是否可连接。若正常,需在防火墙中添加MySQL、MongoDB、NestJS服务的入站允许规则。
- 第三方杀毒软件也可能拦截网络请求,可临时关闭后测试。
内容的提问来源于stack exchange,提问作者MaxM
相关产品推荐
相关产品推荐

