Node.js应用通过Windows身份验证连接SQL Server时为何超时?
解决Node.js通过Windows身份验证连接SQL Server超时问题
问题概述
使用Node.js的mssql库连接SQL Server 2019 Express实例(D15\SQLEXPRESS),已在SQL Server配置管理器启用TCP/IP,端口设为1433,但始终出现连接超时错误。代码如下:
const sql = require('mssql'); const config = { server: "D15\\SQLEXPRESS", database: "DBToDo", port: 1433, options: { encrypt: false, trustServerCertificate: true, connectTimeout: 30000 // 30 seconds }, authentication: { type: "default", options: { trustedConnection: true // Using Windows Authentication } } }; sql.connect(config, err => { if (err) { console.error('Database connection error:', err); } else { console.log('Successfully connected to the database!'); } });
排查与解决方案
1. 确认SQL Server实例的监听端口
SQL Server Express默认可能未固定监听1433,需手动验证并配置:
- 打开SQL Server配置管理器,展开SQL Server网络配置 → SQLEXPRESS的协议,右键点击TCP/IP选择属性
- 切换到IP地址标签,拉至底部的IPAll项,确认TCP端口设为1433,且TCP动态端口为空(避免动态端口覆盖配置)
- 重启SQL Server (SQLEXPRESS)服务
2. 检查防火墙拦截
- 确认Windows防火墙(或第三方防火墙)已添加1433端口的入站允许规则,目标指向SQL Server服务
- 可临时关闭防火墙测试,快速排查是否为防火墙拦截导致的超时
3. 修正连接配置格式
部分mssql版本对嵌套的authentication配置支持存在问题,可简化Windows身份验证的配置写法:
const config = { server: "D15\\SQLEXPRESS", database: "DBToDo", port: 1433, options: { encrypt: false, trustServerCertificate: true, connectTimeout: 30000, trustedConnection: true // 直接将Windows身份验证配置移至options下 } };
同时可尝试将server字段替换为localhost\SQLEXPRESS或服务器IP(如127.0.0.1\SQLEXPRESS),避免机器名解析异常。
4. 测试基础连通性
- 用PowerShell执行
Test-NetConnection D15 -Port 1433,或用telnet D15 1433测试端口是否能正常连通,排除网络层面故障 - 用SQL Server Management Studio(SSMS)以Windows身份验证连接
D15\SQLEXPRESS,确认实例本身可正常访问,排除SQL Server权限或实例故障问题
5. 更新mssql库版本
旧版本mssql可能存在Windows身份验证的兼容性问题,执行以下命令更新至最新版:
npm update mssql
内容的提问来源于stack exchange,提问作者Alican Armut
相关产品推荐
相关产品推荐

