Recently I put my interest in node.js and learned a great about it and quickly move to the express framework. I've tried to connect my express application with mysql database and succeeded. Now I try to authenticate a simple login from connected with mysql database but I can't do that. Still don't get it why it is happening. Bellow here is the code I've used. A help will be greatly welcome.
var mysql = require('mysql');
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'express_db',
password: '12345'
});
connection.connect();
exports.admin_login = function (req, res) {
res.render('./admin/login', {title: 'Please provide your credentials to login'});
};
exports.admin_home = function (req, res) {
var parse = req.body;
var name = parse.name;
var password = parse.password;
var sql = "select * from user where name = " + connection.escape(name) + " and password = " + connection.escape(password);
connection.query(sql, function (err, results) {
if (err) throw err;
if (name == results[0].name && password == results[0].password) {
req.session.regenerate(function () {
req.session.name = results[0].id;
res.render('./admin/home', {username: results[0].name});
});
}
});
Related
Hello I'm just new to Node.js and currently working on session login.
Why can't I set session inside my query function?
Why do I need req.session.save() to save it, but after redirecting to some page session its still not totally set and the page needs to refresh to show session.
Here is my function in setting session
client.query(
"Select id FROM users Where username = '" + req.body.username + "' AND password = '" + req.body.password + "'",
function(err, result) {
if (err) {
return console.error('error running query', err);
} else {
done();
req.session.user_id = result.rows;
req.session.save();
res.redirect('/wall');
}
});
You might want to simplify your example and clarify what libraries you are using. I am assuming you are using express and express-session. I set up a simple example where when you go to to /login?username=yourname page it redirects you to a different page where it shows your name.
var app = require('express')();
var http = require('http').Server(app);
var session = require('express-session');
var mysql = require('mysql')
app.use(session({secret: 'super secret'}));
var client = mysql.createConnection({
host: "My",
user: "private",
password: "configuration",
database: "my_db"
});
app.get('/login', function(req, res, next) {
var sessionData = req.session;
client.query('SELECT * from users where username = ?', [req.query.username], function(err, rows) {
if(err) throw err;
if (rows.length) {
var user = rows[0]
req.session.username = user.username;
req.session.user_id = user.id
res.redirect('/signed_in');
} else {
res.send("user not found")
}
})
})
app.get('/signed_in', function(req, res){
res.send(req.session.user_id + "," + req.session.username);
});
http.listen(3000);
Quentin is right you should look out for sql injections. in the case of node you typically do something like this, depending on what sql library you are using.
client.query(
"Select id FROM users Where username = ? AND password = ?", [req.body.username, req.body.password],
function(err, result) {
// Your code
}
As for why you have to refresh the page after you reload it my guess is something related to done function since i don't know what it is doing in your code. I have no idea why you need to call save, it is not necessary in my example.
In my node.js app I am using the mysql library for database connectivity.
When I start my node server I can query the database perfectly fine – no issues
When I query the database after 5 minutes the server returns the following error:
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
If I restart my node.js server I can query again with no issues…
Here is my code
const mysql = require('mysql');
let connection = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
});
I have used both mysql.createConnection and mysql.createPool…. also tried ending the connection manually with connection.end….
Both results end in the same error.
You need to get a connection from the pool and use that, not query the pool itself. When you get a connection from the pool, the pool will make sure you get a valid connection from the pool. So your code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.getConnection(function(err, connection) {
if (err)
return res.json(err);
connection.query(q, user, (err, results) => {
if (err)
return res.json(err);
return res.json(results);
});
})
});
UPDATE:
You don't need to do separate pool.getConnection and connection.query, you can combine them into a pool.query which will get a connection, do the query and release the connection. So, the updated code would be:
const mysql = require('mysql');
let pool = mysql.createPool({
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database
});
router.post('/subscription', (req, res) => {
const user = req.body;
const q = 'INSERT into Subscription SET ?';
pool.query(q, user, function(err, connection) {
if (err)
return res.json(err);
return res.json(results);
});
});
I am currently developing a node.js backend for a mobile app with potentially many users. However it's my first time in developing node.js. I was following a tutorial on how to connect to a mysql database via mysql pools.
I am able to create a single mysql connection and do queries via my routes.
The problem arises once I establish the file structure mentioned in the tutorial:
dbConnect
-[models]
--users.js
-db.js
-server-ks
I am not getting an error message regarding the connection of the mysql database - even if I enter a wrong password.
// server.js
///////////////////////////// basic setup ///////////////////////////////////
var restify = require('restify');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var db = require('./db');
var users = require('./models/users');
///////////////////////////// initilisation of the server ///////////////////////////////////
var server = restify.createServer({
name: 'testUsers',
});
server.use(restify.bodyParser({ mapParams: true }));
///////////////////////////// Säuberung der URL //////////////////////////////////////////
server.pre(restify.pre.sanitizePath());
///////////////////////////// MySQL Instanz starten //////////////////////////////////////////
db.connect(db.MODE_PRODUCTION, function (err) {
if (err) {
console.log('Unable to connect to MySQL.')
process.exit(1)
} else {
server.listen(8080, function () {
console.log('Listening on port 8080 ...')
})
}
})
///////////////////////////// implementation of the routes ///////////////////////////////////
function send(req, res, next) {
var test = users.getAll();
res.json({ test: 'Hello ' + req.params.name });
return next();
};
My DB.js file looks the following:
var mysql = require('mysql'),
sync = require('async')
var PRODUCTION_DB = 'userDB',
TEST_DB = 'userDB'
exports.MODE_TEST = 'mode_test'
exports.MODE_PRODUCTION = 'mode_production'
var state = {
pool: null,
mode: null,
}
exports.connect = function (mode, done) {
state.pool = mysql.createPool({
connectionLimit: 50,
host: 'localhost',
user: 'user',
password: 'password',
database: 'userDB' // test
//mode === exports.MODE_PRODUCTION ? PRODUCTION_DB : TEST_DB
})
state.mode = mode
done()
}
exports.get = function () {
return state.pool
}
Could it be, that the tutorial spared out an essential part in utilizing mysql pools and node.js?
Thanks in advance for at least trying to answer that question.
Are there better methods sequelize(?) available to create performant connections to a MySQL database?
It looks like creating the pool object does not actually connect to the database. A big clue is that the createPool function is not asynchronous, which is what you would expect if it was actually connecting at that moment.
You have to make use of the returned pool object to perform a query, which IS asynchronous.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
I'm studying Node.js + Express, coding a basic login example. My /login route is set inside the routes/login.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
router.post('/', function(req,res){
connectionpool.getConnection(function(err, connection) {
if (err) {
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
} else {
// Do something
}
});
});
module.exports = router;
I was wondering: how can I make the mysql or the connectionpool visible in the entire application? I don't want to redeclare them on each route file I'll create. I'm looking something like an include or require method.
Any idea?
Create a separate module to act as an interface to retrieving SQL connections like so:
var mysql = require('mysql');
var connectionpool = mysql.createPool({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'database'
});
exports.getConnection = function (callback) {
connectionpool.getConnection(callback);
};
Then in another file:
var connections = require('./connections');
connections.getConnection(function (err, c) {
// Use c as a connection
c.query("select * from table limit 10 ",function(err,rows){
//this is important release part
c.release();
if(!err) {
console.log(rows);
}
});
});
I want to create a manager to interact with mysql, but I'm not able to bring it into the main program. I'm mainly just trying to get the hang of javascript for this stuff (java, c background).
I have two files called main.js and MSYQLConnector.js. I want to use MYSQLConnector from
main.js
var root = __dirname, express = require('express');
var app = express();
var sql = require('./DBConnectors/MYSQLConnector.js');
var a = sql.sqlTest;//????? fail....
MYSQLConnector.js
var sqlTest = function (){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxx'
});
connection.connect();
connection.query('SELECT * from asset', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
};
How can I do the import? Thanks
You need to export the function from your module. Add:
exports.sqlTest = sqlTest;
to the bottom of your MYSQLConnector.js file.
Also, see the nodejs api documentation for more details.
you're almost there, add "exports" in front of it:
exports.sqlTest = function (){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxx'
});
connection.connect();
connection.query('SELECT * from asset', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
};