Can't connect to DB using node.js - sql

I am new to node.js and try to connect to my database. I am using VS 2019 and when debugging while connecting to the local database (which is a copy from that on the server), it works fine and return the data but when I debug it when refer to the database on the server it didn't work.
I got the following error:
ConnectionError: Failed to connect to SQL5075.site4now.net:1433 - 12924:error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1994:
Can anyone help? Thank you
This is my code in VS2019:
var app = require('express')();
app.get('*', (req, res) => {
var sql = require("mssql");
// config for your database
var config = {
//This connection works fine
//user: 'sa',
//password: 'xxxxxxx',
//server: 'localhost',
//database: 'DB_9BD4_info'
// this connect to the server.
user: 'DB_admin',
password: 'xxxxxxx',
server: 'SQL50.xxxxxxx.net',
database: 'DB_9BD4_info'
};
(async function () {
try {
let pool = await sql.connect(config)
let result1 = await pool.request()
.query('select * from info')
// console.dir(result1)
// send records as a response
res.send(result1);
} catch (err) {
console.log(err)
}
})();
sql.on('error', err => {
// error handler
console.log(err);
});
});
//start listening
var port = process.env.PORT || 5321;
app.listen(port, function () {
console.log('Application started on ' + new Date());
console.log("Listening on " + port);
});

I've got the same error. What worked for me was this config object:
const sqlConfig = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
options: {
instanceName: 'instance name',
trustServerCertificate: true,
encrypt: false,
},
};

Related

Azure functions: Exception: TypeError: connection.query is not a function

I have a simple Azure function trying to get all data from a SQL table. The connection is successful and I can connect to the database, but whenever I run the get request, I end up with an error
Exception: TypeError: connection.query is not a function
Stack: TypeError: connection.query is not a function
This is the line throwing the error
connection.query(query, (err, results, fields) => {
this is my index.js azure get function
const express = require('express')
const bodyParser = require('body-parser')
let connection = require('../configs/dbConfig')
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
module.exports = async function (context, req, res) {
const query = 'SELECT * FROM entrys'
connection.query(query, (err, results, fields) => {
if (err) {
const response = { data: null, message: err.message, }
res.send(response)
}
const pokemons = [...results]
const response = {
data: pokemons,
message: 'All entrys successfully retrieved.',
}
res.send(response)
})
}
Am using tedious as the connection driver. my dbconfig
let Connection = require('tedious').Connection;
let pool = {
server: "localhost", // or "localhost"
authentication: {
type: "default",
options: {
userName: "sa",
password: "root",
}
},
options: {
database: "testing",
encrypt: false
}
};
var connection = new Connection(pool);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection
what am I doing wrong, thank you in advance
You should use Request to query.
In the official documentation, I did not see the usage of connection.query. It is not recommended that you use tedious when you are not very familiar with it. I have a sample code here, I hope it helps you.
You can download my Sample Code which use mssql package.
var express = require('express');
var router = express.Router();
let connection = require('../configs/dbConfig')
var Request = require('tedious').Request;
/* GET users listing. */
router.get('/', function(req, res, next) {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
res.send('respond with a resource');
});
module.exports = router;
Test Result:

server.close() gives "server not running" in afterEach mocha hook

I'm trying to run a test suite with mocha, the goal is to start the server beforeEach test case and then
close it afterEach test case.
But for some reason when the afterEach case ignites I get the following error:
Error [ERR_SERVER_NOT_RUNNING]: Server is not running.
The test case passes which means the server is up and running.
I Export the server like this from my app.js file:
var server = app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
});
module.exports = server; // Export server in order to use it in test files
My test file:
describe("loading express", function () {
var server;
before(function (done) {
User.deleteMany(done);
});
beforeEach(function () {
server = require("../app");
});
afterEach(function (done) {
server.close(done);
});
describe("Create user account with valid email address", function () {
describe("Route: POST /signup", () => {
it("201 HAPPY PATH", (done) => {
chai
.request(server)
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
.end((err, res) => {
res.should.have.status(201);
done();
});
});
});
});
});
I believe I need to export a promise.
This is what I got so far:
var server = new Promise(function (resolve, reject) {
app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
resolve();
});
}
module.exports = server; // Export server in order to use it in test files
in test suite:
var server = require('./app.js')
server.then(function() {
....
}
The server is closed by chai-http every time a request is served.
From the chai-http docs:
If you want to keep the server open, perhaps if you’re making multiple requests, you must call .keepOpen() after .request(), and manually close the server down:
E.g:
chai
.request(server)
.keepOpen() // <-- Here
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})

Node js make request to SQL Server, return result

Working with Node.js and am having some trouble understanding how to return the result after making a request to SQL Server. When running independently and writing to the console, I can get the result just fine, however using it as a function and having it return the result is where I am running into problems.
I'm pretty sure I have to use a callback/promise, but don't really understand how either of those are set up. Hoping someone on here can help me out!
Here is my code:
var sql = require("mssql");
var config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'Master'
};
function updateTable() {
var connection = new sql.ConnectionPool(config, function(err) {
var request = new sql.Request(connection);
request.query('select LastName from Persons', function(err, result) {
return result.recordset;
});
});
};
console.log(updateTable());
Basically trying to print the result to the console by calling the function through console.log. Right now it's printing 'undefined', but I assume putting in a callback would do the trick. Again, just need some help understanding how it works and getting it set up. Thanks!
If you just want to print it to the console then you can simply tweak your code as follows:
var sql = require("mssql");
var config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'Master'
};
function updateTable(callback) {
var connection = new sql.ConnectionPool(config, function(err) {
var request = new sql.Request(connection);
request.query('select LastName from Persons', function(err, result) {
callback(result.recordset);
});
});
};
updateTable(console.log);
To send the result from an express handler, assuming >= NodeJS v8:
Wrap the actual database interfacing logic inside an async function which will not block the main thread and export it from your module.
sqlConnector.js
const sql = require('mssql');
const config = {
user: 'username',
password: 'password',
server: 'localhost',
database: 'Master'
};
const updateTable = async () => {
try {
const pool = await sql.connect(config);
const sqlQuery = 'SELECT LastName FROM Persons';
const result = await pool.request().query(sqlQuery);
return result;
} catch (err) {
throw err;
}
};
export.updateTable = updateTable;
In express handler
Import your module which talks with MS-SQL (assumed sqlConnector.js) and mark your handler with the async keyword and return it from res.json at the end.
const sqlConnector = require('sqlConnector');
app.get('/someroute', async (req, res, next) => {
try {
const result = await sqlConnector.updateTable();
return res.status(200).json(result);
} catch (error) {
next(error);
}
});

Typescript return SQL Server connection variable

I am using a method to return SQL Server connection variable.
const sql = require('mssql');
/* sql configuration */
var config = {
user: '***',
password: '***',
server: '***',
database: '***',
port: '***',
multipleStatements: true,
timezone: '+00:00'
};
function getRequest(){
return new Promise(function(resolve, reject) {
sql.close()
sql.connect(config, function (err:any) {
if (err) reject(err);
var sqlrequest = new sql.Request();
//console.log(sqlrequest);
resolve(sqlrequest);
});
});
}
I am calling the connection by below code. but this is not working, the process is not hitting section one. Could any one help me thank you.
getRequest().then(function(sqlrequest:any) {
//not hitting into this section --section 1
sqlrequest.input('ReturnValue',0);
sqlrequest.output('ReturnValue',sql.Int);
sqlrequest.execute('SaveHl7File')
.then(function(recordsets:any, err:any) {
console.log([recordsets0);
}

Request Data from MSSQL with Node.js -- Error

I want to connect and Request from MSSQL using nodejs to link it with magento.
I Am trying to fix it for days now but it ends on the same way...
This is my Error Code:
Connected
{ RequestError: Requests can only be made in the LoggedIn state, not the Connecting state
at RequestError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\errors.js:34:12)
at Connection.makeRequest (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1423:33)
at Connection.execSql (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:1194:19)
at executeStatement (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:41:20)
at Connection.<anonymous> (C:\Workspace\Visual-Code\nodeApi\nodeapi.js:14:9)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.socketError (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:869:14)
at C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connection.js:739:25
at GetAddrInfoReqWrap.callback (C:\Workspace\Visual-Code\nodeApi\node_modules\tedious\lib\connector.js:68:18)
message: 'Requests can only be made in the LoggedIn state, not the
Connecting state',
code: 'EINVALIDSTATE' }
I searched a lot and found similar problems but nothing solved it...
This is my Code maybe you can help me Spot the mistake.
var Connection = require('tedious').Connection;
var config = {
userName: 'Cool userName',
password: 'awesome password',
server: 'amazing server',
options: {
database: 'database',
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("select * from Artikelstamm;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
Set Firewall rule to your DB by adding CleintIP. In Azure SQLDB, there is SET FIREWALL RULE button. You can use it to add IP.
Add this event to your request
request.on("requestCompleted", function () {
connection.close();
resolve(result);
});