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]);
}
});
});
Related
While following this youtube video to learn about node.js
I got this error
$ nodemon index.js
(node:18129) [DEP0096] DeprecationWarning: timers.unenroll() is deprecated. Please use clearTimeout instead.
App server still able to run. However as I am trying to add router to add item as the video, it never go through successfully. However, I would call it half- successfully as I do see the data log in the terminal but never go back to database. as you can see, we can see xxx as name as 40 as price in the terminal after I queried
http://localhost:4000/products/add?name=xxx&price=40
in the browser as in the video around 10:52. (I got it working after hard-coding in the index.js file. Why can't I query it as the video did? ) I am assuming the timers.unenorll() causing this. but i Googled it, all i find is this one, and this one(on https://nodejs.org/en/blog/release/v10.0.0/ page)
but don't know what to do with it. cant' find a solution.please help
$ node -v
v10.0.0
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
app.use(cors());
const SELECT_ALL_PRODUCT_QUERY = 'SELECT * FROM products';
const connection = mysql.createConnection({
host: 'localhost',
user: 'genius',
password: 'genius',
database: 'react_sql'
});
connection.connect(err => {
if(err) {
return err;
}
});
console.log(connection);
app.get('/',(req, res) => {
res.send('go to /products to see the genius gyms')
});
app.get('/products/add', (req, res) => {
const {name, price} = req.query;
//console.log(name, price);
const INSERT_PRODUCTS_QUERY = `INSERT INTO products(name, price) VALUES('${name}',${price})`;
connection.query(INSERT_PRODUCTS_QUERY,(err, results) => {
if(err) {
return res.send(err)
} else {
return res.send('successfully added product')
}
});
});
app.get('/products', (req, res) => {
connection.query(SELECT_ALL_PRODUCT_QUERY,(err,results) => {
if(err) {
return res.send(err)
}
else {
return res.json({
data: results
})
}
});
});
app.listen(4000,() => {
console.log(`Genius gyms listening on
port 4000`)
});
npm install mysql#2.16.0 --save
Just update the mysql library to latest version.
The offender seems to be the mysql module at this spot in the code where you see a call to Timers.unenroll(sequence):
https://github.com/mysqljs/mysql/blob/61b173cbc3e207c5497c6c45c98a4871c01701f3/lib/protocol/Protocol.js#L325
Protocol.prototype._dequeue = function(sequence) {
Timers.unenroll(sequence);
// No point in advancing the queue, we are dead
if (this._fatalError) {
return;
}
this._queue.shift();
var sequence = this._queue[0];
if (!sequence) {
this.emit('drain');
return;
}
this._parser.resetPacketNumber();
this._startSequence(sequence);
};
From various comments on the node.js Github site, it sounds like the API has been deprecated, but won't be removed any time soon. Hopefully, mysql will switch to a substitute at some point. You could inquire on their Github site if you want to know more. The specific issue has already been filed on the mysql site here: https://github.com/mysqljs/mysql/issues/2003 and the current response is that the mysql module does not yet support node.js 10.x.
That presumably means you could rollback your node version to 8.x if you wanted and the issue would probably be gone or just wait for a mysql version that does directly support nodejs 10.x.
First of all, this is one of my first projects in Node.js so I'm very new to it.
I have a project I want to make that is a SOAP (I know, SOAP... backwards compatibility, huh?) interface that connects to an Oracle database.
So I have a WSDL describing what these functions look like (validation for addresses and stuff) and I have a connection to the database.
Now when using the SOAP npm module, you need to create a server and listen using a service that allows you to respond to requests. I have a separate file that contains my SOAP service but this service should do queries on the database to get its results.
How would I go about sort of 'injecting' my database service into my SOAP service so that whenever a SOAP call is done, it orchestrates this to the correct method in my database service?
This is what my code looks like:
databaseconnection.js
var oracledb = require('oracledb');
var dbConfig = require('../../config/development');
var setup = exports.setup = (callback) => {
oracledb.createPool (
{
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err, pool)
{
if (err) { console.error(err.message); return; }
pool.getConnection (
function(err, connection)
{
if (err) {
console.error(err.message);
return callback(null);
}
return callback(connection);
}
);
}
);
};
databaseservice.js
var DatabaseService = function (connection) {
this.database = connection;
};
function doSomething(callback) {
if (!this.database) { console.log('Database not available.'); return; }
this.database.execute('SELECT * FROM HELP', function(err, result) {
callback(result);
});
};
module.exports = {
DatabaseService: DatabaseService,
doSomething: doSomething
};
soapservice.js
var myService = {
CVService: {
CVServicePort: {
countryvalidation: function (args, cb, soapHeader) {
console.log('Validating Country');
cb({
name: args
});
}
}
}
};
server.js
app.use(bodyParser.raw({type: function(){return true;}, limit: '5mb'}));
app.listen(8001, function(){
databaseconnection.setup((callback) => {
var temp = databaseservice.DatabaseService(callback);
soapservice.Init(temp);
var server = soap.listen(app, '/soapapi/*', soapservice.myService, xml);
databaseservice.doSomething((result) => {
console.log(result.rows.length, ' results.');
});
});
console.log('Server started');
});
How would I go about adding the databaseservice.doSomething() to the countryvalidation soap method instead of 'name: args'?
Also: I feel like the structure of my code is very, very messy. I tried finding some good examples on how to structure the code online but as for services and database connections + combining them, I didn't find much. Any comments on this structure are very welcome. I'm here to learn, after all.
Thank you
Dieter
The first thing I see that looks a little off is the databaseconnection.js. It should be creating the pool, but that's it. Generally speaking, a connection should be obtained from the pool when a request comes in and release when you're done using it to service that request.
Have a look at this post: https://jsao.io/2015/02/real-time-data-with-node-js-socket-io-and-oracle-database/ There are some sample apps you could have a look at that might help. Between the two demos, the "employees-cqn-demo" app is better organized.
Keep in mind that the post is a little dated now, we've made enhancements to the driver that make it easier to use now. It's on my list to do a post on how to build a RESTful API with Node.js and Oracle Database but I haven't had a chance to do it yet.
I am using Promised-Mongo to connect MongoDB with Promises from NodeJS backend code. It worked fine, until I enabled MongoDB's client access control. When I run this code, I get "could not authenticate" message":
var pmongo = require('promised-mongo').compatible();
var db = pmongo('myusername:mypassword#localhost/mydb', ['candidates']);
db.candidates.save(req.body)
.then(function () {
// never reached here
})
.catch(function (e) {
// it reached here, where e.message says "could not authenticate"
});
Pure MongoDB code (i.e. no Promises...) works fine:
var mongodb = require('mongodb');
var uri = 'mongodb://myusername:mypassword#localhost/mydb';
mongodb.MongoClient.connect(uri, function (err, db) {
if (err) {
// never reached here
}
var candidates = db.collection('candidates');
candidates.insert(req.body, function(err, result) {
if (err) {
// never reached here
}
res.send('{result: success}');
});
});
Any idea?
Per several issues in the github repository (see here and here) it looks like using this library with authentication is totally broken. Per the second link, most people seem to be wrapping the official library with a promise via something like promisify, bluebird, or a thin custom wrapper.
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.
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.