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')
}
})
To identify if SQL SERVER database is SSL enabled or not, run the following query: "SELECT session_id, encrypt_option FROM sys. dm_exec_connections". It should be run by Database Administrator.
In SQL Server Configuration Manager, in the console pane, expand SQL Server Network Configuration. Right-click Protocols for <instance Name>, and then select Properties. Choose the Certificate tab, and then select Import. Select Browse and then select the certificate file.
In SQL Server Configuration Manager, expand SQL Server Network Configuration, right-click Protocols for <server instance>, and then select Properties. On the Certificate tab, select the desired certificate from the Certificate drop-down menu, and then click OK.
I had the same error message (Failed to connect to xxx:1433 - self signed certificate
). Then I used trustServerCertificate: true
. This fixed the error for me.
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,
}
}),
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..');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With