'Certificate error when connecting to SQL Server
When trying to connect to SQL Server, I get the following error:
(node:9364) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to 10.120.6.11:1433 - self signed certificate
When I use SQL Server 2014, it works normally.
Note: You need a vpn to connect.
Code:
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')
}
})
Solution 1:[1]
I encountered the same problem on my project. I manage to solve the problem by adding trustServerCertificate: true
Example (NestJS and TypeORM usage):
TypeOrmModule.forRoot({
type: 'mssql',
host: 'localhost\\SQLEXPRESS',
username: 'sa',
password: 'root',
database: 'DB',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
extra: {
trustServerCertificate: true,
}
}),
Solution 2:[2]
What works with me, with the full script:
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..');
});
Solution 3:[3]
If you're using a connection string:
sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Trusted_Connection=True;TrustServerCertificate=True;');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Adrian Mole |
| Solution 3 | Pramuditha Chamikara |
