How to create a awaitable connection with mysql using node.js - mysql

I'm new with Node.js and I'm trying to create a async method with Node.js, because I need to check a row inside of my database and then decide what to do with it. So I created a file called sql-service.js
const sql = require('mysql');
var connection = sql.createConnection({
host: '0.0.0.0',
user: 'foo',
password: 'fooo'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
console.log(connection.state);
module.exports.SignUpUser = (email,password)=>{
connection.query('select * from usuario', function(error, results, fields) {
console.log(results);
});
}
And inside of my Controller :
const sqlService = require('../services/sql-service');
exports.post = async(req,res,next)=>{
const Email = req.body.Email;
const Passw = req.body.Password;
console.log(dateT.getdate());
if (fluentValidation.validateEmail(Email) && fluentValidation.isValidLenght(Passw)) {
try {
await sqlService.SignUpUser(Email,Passw);
//emailService.send(req.body.Email,'Nome','Bem vindo ao hanggu');
} catch (error) {
console.log(error);
}
res.status(201).send({
Email: "Valid " + req.body.Email,
Password: Passw.length,
Send: 's '//Date : dateT.getDateTime()
});
} else {
res.status(500).send({
Error: "Email invalid"
})
}
}
It does connect but the result that I got it's undefined, I tried
console.log('The solution is: ', results[0].usuario);
But still.

what schema you select?
var connection = sql.createConnection ({
host: '0.0.0.0',
user:'foo',
password : 'fooo',
database : 'you_db'
});
test

Related

Cannot use .query commands leaves to an error in nodejs

Problem:
I have created a node application there I am adding admin to the database like this in userModal.js file.
var bcrypt = require('bcryptjs');
var sql = require('../db.js');
module.exports.save_admin = (new_admin,callback) =>{
bcrypt.genSalt(10,(err, salt)=> {
bcrypt.hash(new_admin.password, salt, (err, hash)=> {
new_admin.password = hash;
if(err){
throw err;
}
else{
console.log(new_admin.password);
sql.query("INSERT INTO administrators set ?", new_admin, callback);
}
});
});
}
This is how I am calling this function from the controller.
var admin = {
first_name: req.body.first_name,
last_name: req.body.last_name,
organization: req.body.organization,
admin_level: req.body.admin_level,
user_identity: req.body.identity,
username: req.body.username,
password: req.body.password
};
User.save_admin(admin, (err,user) => {
if (!err) {
res.json({ state: true, msg: "data Inserted" });
} else {
res.json({ state: false, msg: "data Is Not Inserted" });
}
});
This is how I have configured the database in db.js file.
'user strict';
var mysql = require('mysql');
//local mysql db connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydatabase'
});
connection.connect(function(err) {
if (!err){
console.log("Database connection succeeded...!");
}
else{
console.log('Error in DB connection :'+JSON.stringify(err,undefined, 2));
}
});
module.exports = connection;
module.exports = {
"secret": "myapplicationsecret"
};
This setup leaves me this error.
sql.query("INSERT INTO administrators set ?", new_admin, callback);
^
TypeError: sql.query is not a function

Data shows on server response, but not on browser - MySQL Node.js

When I run http://localhost:1337 I get this as my output Hello, [object Object] but on the server response, the output is Hello, David James. It works on the server response but not on the browser.
app.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mywebsite'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error');
} else {
console.log('Connected');
}
});
app.get('/', function(req, res) {
connection.query("SELECT Name FROM chat", function(error, rows, fields) {
if(!!error) {
console.log('Error in the query');
} else {
console.log('SUCCESS!\n');
console.log(rows);
res.send('Hello, ' + rows);
}
});
});
app.listen(1337);
Send it back with JSON.stringify
res.send('Hello, ' + JSON.stringify(rows))

Receiving a token from a clicked email

I'm working on a web application with some team members and I have been tasked with the Password recovery. We are using mysql and node.js for the back-end and API layer. With the following npm packages: nodemailer, mysql, express, body-parser and bcrypt.
The issue at hand is I don't actually know how to create a link with a bcrypt token and then recive the token and interpret it and then send it to the html page/form with the user data.
I haven't tested the code as of yet but some input would be great:
var urlencodedParser = bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.urlencoded({
extended: true
}));
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail#gmail.com',
pass: 'yourpassword'
}
});
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
//Change DB name to the one you make.
database: 'projectracetrack'
});
//User clicks on link in email.
app.get('/recover/:token', function(req, res) {
//here
});
app.post('/forget', urlencodedParser, function(req, res) {
let sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
db.connect(function(err) {
if (err) throw err;
db.query(sql, [req.body.email.toString()], function(err, result) {
if (err) throw err;
console.log(result);
//Comparing email to database
if (result.email.toLowerCase() !== req.email.toLowerCase()) {
//send reply that email
return res.send("Your email does not exist in the database, please use the registration page.");
} else {
var token;
//encripting the token
bcrypt.hash(result.username, saltRounds, function(err, hash) {
if (err) throw err;
token = hash;
sql = "INSERT INTO racers (RecoveryToken, RecoverTimeOut) WHERE email = " + result.email + " VALUES ? LIMIT 1";
//inserting the token and data to the database HERE!!
// 1 hour
var data = [
[token,
Date.now() + 3600000 // 1 hour
]
];
db.query(sql, [data], function(err) {
if (err) throw err;
});
var mailOptions = {
from: 'youremail#gmail.com',
to: result.email,
subject: 'Project Racetrack Password Recovery',
text: 'Dear ' + result.username + '\n\n\
This is a confermation that you would like to recover your password please click on the link:' +
'http://' + req.headers.host + '/recover/' + token + '\n\n\
If this has not been requested by you please contact our customer suppport\n\n\
Kind Regards\n\
Team'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
});
}
});
});
});

NodeJS + Socket.IO + Mysql

I'm using socket.io in order to send message to the user when he join my site and initializing his details using cookie sent by the client. After a while and few refreshes performed my queries stop working.
Here's my code:
io.on('connection', function(socket) {
var user = false;
socket.on('hash', function(hash, gameType) {
socket.join(gameType);
query('SELECT * FROM `users` WHERE `hash` = ' + pool.escape(hash), function(err, row) {
if((err) || (!row.length)) return socket.disconnect();
user = row[0];
users[user.steamid] = {
socket: socket.id,
balance: parseInt(row[0].balance)
}
socket.emit('message', {
balance: row[0].balance,
type: 'hello',
user: row[0].steamid
});
}
}
function query(sql, callback) {
console.log(callback);
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
logger.info('DB Connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/site.log' }
]
});
var logger = log4js.getLogger();
var pool = mysql.createPool({
connectionLimit : 10,
database: 'test',
host: 'localhost',
user: 'root',
password: 'pw'
});
process.on('uncaughtException', function (err) {
logger.trace('Strange error');
logger.debug(err);
});
my guess is the reason is you exhaust the connection pool.
if(err) return callback(err); << after some erros here
connection.release(); << not released if there is an error
just release the connection before this line

Terminating a callback in nodejs

I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?
Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});