新手请教在Node.js中使用mssql模块连接SQL数据库并返回数据?

新手请教连接MSSQL数据库并返回数据问题:

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));

// mssql模块的简单使用
const sql = require('mssql');
// DB configuration
const dbConfig = {
  user: 'sa',
  password: 'sa123',
  server: 'localhost',
  database: 'test',
  port: 1433,
  pool: {    //连接池的概念
        max: 10,
        min: 0,
        idleTimeoutMillis: 3000,
    },
    options: {
        encrypt: false,  
        trustServerCertificate: false, //信任服务器证书
    },
};

var conn = new sql.ConnectionPool(dbConfig);
  //console.log(conn);
var req = new sql.Request(conn);
 app.post('/login', (req,res) => {
    const { username, password } = req.body;
    //获取页面输入数据
    var us = req.body.username;
    var pw =req.body.password;
    sql.connect(conn).then(function() {
    //字符串拼接形式查询数据库是否有数据
        new sql.Request().query("select * from Users where Name = '" + us + "' and Password = '" + pw + "'"  ,function (err,data) {
            if (err) {
                console.log(err);
            }
            //如果数据库有数据rowsAffected则返回1大于零
            else if (data.rowsAffected>0) {
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
                res.end("登录成功");
            }
            else {
                res.writeHead(200,{"Content-Type":"text/html;charset=utf8"});
               
                res.end("用户名或者密码不正确");
            }
        })

    })

    })
        app.listen(3000, () => {
    console.log('Server is running on port 3000');
        });

运行后监听到页面传来的数据后报错
TypeError TypeError: The "config.server" property is required and must be of type string.

不知道错在哪里?

阅读 481
1 个回答

在 Node.js 中使用 mssql 模块连接 SQL Server 时出现 TypeError: The "config.server" property is required and must be of type string 错误,主要原因是连接池配置方式不正确。以下是解决方案和优化建议:

错误修复方案

  1. 直接传递配置对象给 sql.connect()
    问题在于创建 ConnectionPool 实例后,又将其传递给 sql.connect()。应改为:

    // 错误方式
    var conn = new sql.ConnectionPool(dbConfig);
    sql.connect(conn);  // 导致错误
    
    // 正确方式
    sql.connect(dbConfig).then(() => {
      // 查询代码
    });
  2. 使用连接池的正确写法
    若需显式使用连接池,应调用其 connect() 方法:

    const pool = new sql.ConnectionPool(dbConfig);
    pool.connect().then(() => {
      const request = pool.request();
      request.query("SELECT ...");
    });

安全优化建议

  1. 参数化查询防止 SQL 注入
    当前代码存在严重安全风险(字符串拼接查询):

    // 危险写法(易受SQL注入攻击)
    .query("select * from Users where Name = '" + us + "' ...")
    
    // 安全写法(参数化查询)
    new sql.Request()
      .input('username', sql.NVarChar, us)
      .input('password', sql.NVarChar, pw)
      .query('SELECT * FROM Users WHERE Name = @username AND Password = @password');
  2. 连接池配置优化
    根据实际负载调整参数(参考最佳实践):

    pool: {
      max: 10,        // 最大连接数(避免过高导致资源耗尽)
      min: 2,         // 最小空闲连接(建议>0)
      idleTimeoutMillis: 30000, // 空闲超时(单位毫秒)
      acquireTimeoutMillis: 5000 // 获取连接超时
    }

完整修正代码

const sql = require('mssql');
const dbConfig = {
  user: 'sa',
  password: 'sa123',
  server: 'localhost', // 确保是字符串
  database: 'test',
  port: 1433,
  pool: { max: 10, min: 2, idleTimeoutMillis: 30000 },
  options: { encrypt: false, trustServerCertificate: false }
};

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  try {
    await sql.connect(dbConfig); // 直接传递配置对象
    const result = await sql.query`
      SELECT * FROM Users 
      WHERE Name = ${username} 
      AND Password = ${password}`;
    
    result.recordset.length > 0 
      ? res.status(200).send("登录成功")
      : res.status(401).send("用户名或密码错误");
  } catch (err) {
    console.error("数据库错误:", err);
    res.status(500).send("服务器内部错误");
  } finally {
    sql.close(); // 关闭连接
  }
});

常见排查点

  1. 网络与端口检查

    • 使用 telnet localhost 1433 验证端口是否开放
    • 确认 SQL Server 已启用 TCP/IP 协议
  2. 身份验证模式
    确保 SQL Server 启用了 混合身份验证模式(SQL + Windows)
  3. 防火墙设置
    在 Windows 防火墙中允许 1433 端口入站
  4. 驱动依赖
    安装最新版 mssql 模块(支持 TLS 等新特性):

    npm install mssql@latest

连接池工作原理:连接池会缓存数据库连接,避免频繁创建/销毁开销。当请求到达时,直接从池中分配空闲连接;使用完毕后归还到池中,而非真正关闭。合理配置可提升性能 30% 以上。

通过以上修正,既可解决配置错误,又能提升安全性和性能。若仍存在问题,建议检查 SQL Server 错误日志(路径:C:\Program Files\Microsoft SQL Server\MSSQLXX.MSSQLSERVER\MSSQL\Log\ERRORLOG)。

推荐问题