How I can write this code to work properly in nodejs - html

I have config.js in my nodejs project
var mysql = require('mysql');
var db_name = 'node';
var client = mysql.createClient({
user: 'root',
password: 'pass',
});
client.query('USE '+db_name);
I have used it as config file for the project. How I can use this code to call a mysql query.
I have this code in user.js
var global = require('./config.js');
this.CheckUserValid = function (login, pass) {
var sql = "SELECT * FROM `user` WHERE login = ? AND pass= ?";
global.client.query(sql, [login, pass], function selectResutl(err, results, fields) {
if (!err) return results;
else
throw err;
});
}
TypeError: Cannot call method 'query' of undefined
at Object.CheckUserValid (C:\wamp\www\Node\user.js:6:19)
Can someone help me to let me know how I can do this in better way.Actually I am using asp.net mvc in my past so I have tried it. Do someone tell me the better way to write code in nodejs.

When you require() a file/module, the result you get is whatever the module is exporting through the exports property. Anything else is encapsulated in the module and cannot be accessed from the outside. In your case, at the end of config.js you can add:
exports.client = client;
This way it will be accessible whenever you require() your config.js.
This way of creating modules is defined in the CommonJS spec:
http://commonjs.org/specs/modules/1.0/
http://wiki.commonjs.org/wiki/Modules/1.1
edit: and since commonjs.org seems to be down, here is another link with information about this type of module: http://dailyjs.com/2010/10/18/modules/

Related

How to connect ReactJS with Backend like Mysql

I am new to reactJS...
I am familiar with python-django.. now i wanna create backend for my react app.
used react for just front end purpose.. is their a way to communicate my react frontend with react own backend?
I am using MySQL Database.. is their any better way to create API in react Backend?
i knew this connection part alone,
var mysql_conn = require('mysql')
var connection = mysql_conn.createConnection({
host : 'localhost',
database : 'my_db'
});
connection.connect()
connection.query('SELECT _data AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
any suggestion ? shall i use any framework like expressJS with React?

Connect Node with mysqli module?

I want to connect Node JavaScript with Mysqli. I have downloaded the mysqli module using following command.
npm install mysqli
And Then Create JavaScript file with following code.
var Mysqli = require('mysqli');
// incoming json
let conn = new Mysqli ( {
host: "localhost",
user: "root",
password: "",
database: "ll"
} );
conn.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM post", function (err, result) {
if (err) throw err;
console.log(result);
});
});
But not able to connect to database.
I have used following Packages.
https://www.npmjs.com/package/mysqli
You have a typo here:
conn.query
Unless, of course, you wrote the code here again. I am sure you would have figured that out by now, but still... After all, this is the first thing that comes up when someone searches for mysqli nodejs.
If connecting to mysql db is the goal, then I suggest you to use mysql module.
install mysql module by running npm install mysql
below is the sample code for how to use the mysql module
const mysql = require('mysql');
const conn = mysql.createConnection(
{
host:'your_host', //localhost in your case
user:'db_user', // root in your case
password: 'password', //blank string in your case
database:'your_db_name' //'ll' in your case
});
//executing the queries
conn.query('SELECT * from post',function(err,result){ //result of the query is stored in 'result' and the error, if any, are stored in err
if(err)
{
console.log(err);
}
else
{
console.log(result);
}
});
click this link for further information
The module which you're using seems to be a newer one and which is not stable.
Consider using mysql module which has been accepted by many developers, it has a great documentation and an active github community + google mailing list and IRC channel.

using mysql in Electron

Im trying to use mysql in electron but i'm running into this error
TypeError: Invalid data, chunk must be a string or buffer, not object
at Socket.write (net.js:667)
at Protocol.<anonymous> (Connection.js:100)
with this code
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'host address',
user: 'username',
password: 'pw',
database: 'db name',
});
con.connect(err => {
if(err) throw err
})
con.query('select * from BOOKS', (err2, result) => {
if(err2) {
throw err2;
}
console.log(result);
})
if i paste this into a test.js file and run it with node then it runs 100% fine without errors, so im not really sure where im going wrong here
So it turns it my issue had something to do with the fact that I was running Angular on electron. if I put that code inside my Angular code it would error out but if I put it in the index.html it would run fine.
So I just made a little proxy function in the index.html for connecting to the DB and making queries, then i'd jsut call it from inside the Angular app without a problem like window.mysqlQuery(queryString)

Express JS how to include node-mysql object from a different file

I want to include my mysql connection from the same file(in case I have to change sql password or anything I don't want to change in a many files).
Here is my mysql.js file:
module.exports = require('mysql').createConnection(
{
host : 'localhost',
user : 'admin',
password : 'xxxxxxxx',
database : 'database'
}
);
and I want to use like this:
var connection = require(__dirname + '/../../../mysql');
connection.connect();
.
.
.
My problem is it's working only once. When I start the server I can query without any issues, but in the second query I got the following error message in the console:
"Cannot enqueue Handshake after invoking quit."
Does anybody has an idea why not working?
Apparently you no longer need to call connect() after createConnection(), it'll be handled for you on query, if you like.
From the docs:
However, a connection can also be implicitly established by invoking a
query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) { // connected!
(unless err is set) });
Depending on how you like to handle your
errors, either method may be appropriate. Any type of connection error
(handshake or network) is considered a fatal error, see the Error
Handling section for more information.
Other than that, you may be calling connect() before calling end() on the same connection, you might want to check for that.
Thanks the help, but I found a solution for my problem. I just created the variables on my mysql.js file then I exported them like this:
var host = 'localhost';
module.exports.localhost = localhost;
After I can use it on another js file:
var connection = require(__dirname + '/../../../mysql');
connection.localhost;
I found it on this article:
http://openmymind.net/2012/2/3/Node-Require-and-Exports/

How to use existing wamp's MySQL databases in node.js?

I already have WAMP server installed on my machine. Can I be able to access MySQL databases created on WAMP's MySQL using node-mysql module?
Actually, I tried this code, its running without errors but unable to fetch the database(or tables):
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "database_name"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM table_name', function (error, rows, fields) {
console.log('The first field is: ', rows[0].field);
});
});
}).listen(8001);
console.log("running on localhost:8001");
Try adding request.resume(); before your 'end' event handler.
In node v0.10+, streams start out in a "paused" state that allow you to .read() specific sized chunks or you can use them like the old streams by attaching a 'data' event handler which causes the stream to be continuously read from.
Calling request.resume(); will also switch to the old stream mode, effectively discarding the request data (because there are no 'data' event handlers) so that your 'end' event handler will be called.