node.js mssql - can't get simple sample to work - node.js

I am trying to run the simplest hello world with Node.js and the mssql package.
https://www.npmjs.org/package/mssql
I create a new folder, with an empty JS file (app.js)
I copy and paste the sample from the mssql package page to the js file.
I only change the config object with my DB connection settings.
I run npm install mssql which is successful.
I run node app.js
What happens is that the code doesn't get into the callback after creating a connection. So in the code below:
var connection = new sql.Connection(config, function(err) {
alert(1);
...
//more code...
});
I never get to the alert. No exceptions or errors either
I am probably missing something... Can you please help me spot it?
Update: I should mention that the DB is on Azure...

Try this on your server side it works fine on my end:
var sql = require("mssql");
var dbConfig = {
user:'sa',
password:'password1',
server:'serverName',
database:'DBName'
};
var connection = new sql.Connection(dbConfig, function (err) {
console.log(err);
var request = new sql.Request(connection);
request.query("Select 'Hello World' as var1", function (err, recordset, returnValue) {
if (!err ){
console.log(recordset) ;
}else{
console.log(err)
}
});
});

OK, after digging a bit in the docs for Tedious, I found out that if the DB is on Azure you must include options: {encrypt: true} in your configuration object.
Now everything is working as expected.

Related

Electron/NodeJS Connecting to SQL Server using mssql not working

I'm new to Electron and trying to make 1 st application in which I need to connect it to a SQL server database for data storing/retrieving. I've have installed this plugin (https://www.npmjs.com/package/mssql#connect-callback) and followed their instructions but got no success regarding the connection. The weird part is that I also get no error or whatever showing in the console so I'm totally lost. Any help would be much appreciated, thank you guys.
Ps: I'm sure that there's no problem with the database since I can still connect to it using the same config setting below with a database client manager tool.
Below is the code I've used for simple testing connection.
<script type="text/javascript">
$(document).ready(function () {
const electron = require('electron');
const sql = require('mssql');
const config = {
user: 'ql*****',
password: 'qlh****',
server: '123.20.****',
database: 'QLHS'
};
async () => {
try {
await sql.connect(config);
const result = await sql.query`select * from DM_DONVI`;
console.dir(result);
} catch (err) {
console.log(err);
}
};
});
</script>
The link you provided is working. I tried the same. The error log can be seen in view->Toogle Developer Tools. The issue is you need install mysql.
npm install mysql --save
Then the code works fine.
Thank you Mr :D Actually, the thing that didn't work in my original post is the async part. Changing that to this and everything is fine now:
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from DM_DONVI', function (err, recordset) {
if (err) {
console.log("Something went wrong")
}
else {
var result = JSON.stringify(recordset);
console.log(recordset.recordsets[0]);
}
});
});

Aerospike works ok for 1 - 4 hours before defaulting to a connection error

I have been working with the Aerospike Node.js client for a while now, and I've noticed that if I run the server for more than two hours, if I make a connection call to an Aerospike database I get the following error:
ERROR(23159) [connect.cc:69] [Connect] - Connecting to Cluster Failed
Before this happens, execution goes smoothly and without a hitch. I'm using Aerospike coupled with Express to store and retrieve user content. This is one of the endpoints I have written
app.get("/api/content/:id",function(req,res){
aero.client(aeroSec.generateConfig()).connect(function(err, db){
if(err.code != aero.status.AEROSPIKE_OK) return res.status(403).send();
var options = {};
options.filters = [filter.equal("secindex", req.params.id)];
var query = db.query("ns","posts",options);
var data;
var count = 0;
var s = query.execute();
s.on("data",function(rec){
data = rec;
});
s.on("error",function(err){
data = err;
});
s.on("end",function(){
db.close();
if(data == undefined) res.status(404).send("NOTHING FOUND");
else res.status(200).send(data);
});
});
});
In the interest of full disclosure, I am not querying an index that doesn't exist. A search in the Aerospike forums suggested that I comment out db.close() out of my endpoints, which only slows down the problem and doesn't eliminate it. The error started happening when I connected to a Aerospike database hosted on another server, so I decided to query a local server instead only to find the same error after two hours of normal operation.
Does anyone know what to do? I really like Aerospike as a database, but if these problems persist I will have no other choice but to go to another NoSQL database.
The code snippet shows that application creates as many client objects as number of requests received. The common usage is, a single client object is created and this is shared for all communications to Aerospike server. Another clarification is, client.connect() is a synchronous API call. And there is a sample web application in node.js using express and Aerospike. Here is the link. Please refer here for more clarifications.
The above code can be refactored like this
var aerospike = require('aerospike');
var express = require('express');
var app = express();
var aerospikeConfig = {
// add a node in the cluster.
hosts: [{addr: "192.168.0.1", port: 3000 }]
}
var client = aerospike.client(aerospikeConfig);
// client.connect() is a synchronous API call.
client.connect(function(err, client) {
if(err.code != aerospike.status.AEROSPIKE_OK) {
// application should exit or re-attempt the connect call.
// If connect call fails, connection with Aerospike server is
// is not established. Subsequent aerospike API calls will fail.
return err;
}
});
app.get("/api/content/:id",function(req,res){
var options = {};
options.filters = [filter.equal("secindex", req.params.id)];
var query = client.query("ns","posts",options);
var data;
var count = 0;
var s = query.execute();
s.on("data",function(rec){
data = rec;
});
s.on("error",function(err){
data = err;
});
s.on("end",function(){
client.close();
if(data == undefined) res.status(404).send("NOTHING FOUND");
else res.status(200).send(data);
});
});
Thanks

Problems Deploying a Node.js app on Heroku Using MongoLab

I'm attempting to deploy a very simple app to Heroku. The code for the application can be found on Ray Wenderlich's site, here: http://www.raywenderlich.com/61078/write-simple-node-jsmongodb-web-service-ios-app I keep getting the same error whenever I try to have Heroku compile the code...
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
var mongoPort = 41140;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort)); //B
mongoClient.open(function(err, mongoClient) { //C
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1); //D
}
var db = mongoClient.db("heroku_app23491233"); // E
collectionDriver = new CollectionDriver(db); //F
});
When I type heroku logs, the error I get comes from if (!mongoClient) above...
app[web.1]: Error! Exiting... Must start MongoDB first
I'm sure the problem lies somewhere in my attempt to connect to the MongoLab database. I've copied the URI from MongoLab and I've created a user with the proper credentials.
I can connect to localhost just fine with very similar code, so I'm not sure what is going wrong in this example.
Thank you.
Based on the docs, my best guess is that it's because the Server constructor expects the first argument to contain only the host name (in the case of your MongoLab, ds041140.mongolab.com). However, I think you can pass your connection string into MongoClient.connect:
// Make sure to replace username and password with the proper values.
var mongoHost = "mongodb://username:password#ds041140.mongolab.com:41140/heroku_app23491233";
MongoClient.connect(mongoHost, function(err, db) {
if (err) return console.log(err);
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
db.close();
if (err) return console.log(err);
console.log('Okay', result);
});
});
Documentation Page For MongoClient
Hopefully that helps!

Express keeping connection open?

I'm using node js, express and postgresql as backend.
This is the approach I used to make a rest API:
exports.schema = function (inputs, res) {
var query = knex('schema')
.orderBy('sch_title', 'asc')
.select();
query.exec(function (err, schemas) {
if(err){
var response = {
message: 'Something went wrong when trying to fetch schemas',
thrownErr: err
};
console.error(response);
res.send(500, response);
}
if(schemas.length === 0){
var message = 'No schemas was found';
console.error(message);
res.send(400, message);
return;
}
res.send(200, schemas);
});
};
It works but after a while postgres logs an error and it's no longer working:
sorry, too man clients already
Do I need a close each request somehow? Could not find any about this in the express docs. What can be wrong?
This error only occurs on production server. Not on developing machine.
Update
The app only brakes in one 'module'. The rest of the app works fine. So it's only some queries that gives the error.
Just keep one connection open for your whole app. The docs shows an example how to do this.
This code goes in your app.js...
var Knex = require('knex');
Knex.knex = Knex.initialize({
client: 'pg',
connection: {
// your connection config
}
});
And when you want to query in your controllers/middlewares...
var knex = require('knex').knex;
exports.schema = function (req, res) {
var query = knex('schema')
.orderBy('sch_title', 'asc')
.select();
// more code...
};
If you place Knex.initialize inside an app.use or app.VERB, it gets called repeatedly for each request thus you'll end up connecting to PG multiple times.
For most cases, you don't need to do an open+query+close for every HTTP request.

How to init native Mongo in NodeJS with at Sign in password

I am trying to figure out how to connect to my mongodb db using the native node mongo driver and I have two issues:
My password contains an # sign making it break the normal user:pass#host connection string format
How do I list databases from what I have below?
Any ideas on how to address this?
Here is an attempt which does not work:
var Mongo = require('mongodb');
var server = new Mongo.Server('mongodb://myhost', 27017);
var db = new Mongo.Db('test', server);
db.open(function(err, db) {
console.log(err); //unable to connect
});
For future readers, I was able to resolve this with the connection option uri_decode_auth. You will need to encodeURIComponent(password) before embedding it in the connection string.
Here's a complete working example:
MongoClient.connect(connection, { uri_decode_auth: true }, function(err, db) {
if(err) {
return cb(err);
}
db.admin().listDatabases(function(err, dbs) {
console.log(dbs);
});
});
As mentioned on this answer:
The solution is to replace # with %40
I tested with the C# driver and it works like a charm.

Resources