连接到SQL Server时出现证书错误

gk7wooem  于 2023-01-01  发布在  SQL Server
关注(0)|答案(4)|浏览(505)

尝试连接到SQL Server时,出现以下错误:
(node:9364)未处理承诺拒绝警告:连接错误:无法连接到10.120.6.11:1433-自签名证书
当我使用SQL Server 2014时,它工作正常。
注意:您需要一个vpn来连接。
代码:

const config = {
  port: parseInt(process.env.DB_PORT, 10),
  server: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_Database,
  stream: false,
  options: {
    trustedConnection: true,
    encrypt: true,
    enableArithAbort: true,
    trustServerCertificate: false,

  },
}

sql.connect(config).then(pool => {
  if (pool.connecting) {
    console.log('Connecting to the database...')
  }
  if (pool.connected) {
    console.log('Connected to SQL Server')
  }
})
e37o9pze

e37o9pze1#

我得到了同样的错误信息(Failed to connect to xxx:1433 - self signed certificate)。然后我使用了trustServerCertificate: true。这为我修复了错误。

yvfmudvl

yvfmudvl2#

我在我的项目中遇到了同样的问题。我设法通过添加trustServerCertificate: true解决了这个问题
示例(NestJS和TypeORM用法):

TypeOrmModule.forRoot({
  type: 'mssql',
  host: 'localhost\\SQLEXPRESS',
  username: 'sa',
  password: 'root',
  database: 'DB',
  entities: [__dirname + '/**/*.entity{.ts,.js}'],
  synchronize: true,
  extra: {
    trustServerCertificate: true,
  }
}),
ktca8awb

ktca8awb3#

对我有效的是,完整的脚本:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
    var sql = require("mssql");
    // config for your database
    var config = {
        user: 'sa',
        password: 'P@ssw0rd',
        server: 'WIN-N4J1057LVFV', 
        database: 'WIN-PAK_ALL',
        synchronize: true,
        trustServerCertificate: true,
    };
    // connect to your database
    sql.connect(config, function (err) {
        if (err) console.log(err);
        // create Request object
        var request = new sql.Request();
        // query to the database and get the records
        request.query('select * from cardHistory', function (err, recordset) {
            if (err) console.log(err)
            // send records as a response
            res.send(recordset);
        });
    });
});
var server = app.listen(5000, function () {
    console.log('Server is running..');
});
mefy6pfw

mefy6pfw4#

如果使用连接字符串:

sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Trusted_Connection=True;TrustServerCertificate=True;');

相关问题