Nodejs Mysql query throw err - mysql

I try to register my user into a mysql database but an error appears
I checked my database and the user is added but the error is still here.
The Error :
throw err; // Rethrow non-MySQL errors
My code :
create : function(body, callback)
{
var bind = [];
for(prop in body) {
bind.push(body[prop]);
}
let sql = `INSERT INTO users(email, firstname, lastname, password, language, currency, seed) VALUES (?, ?, ?, ?, ?, ?, ?)`;
pool.query(sql, bind, function(err, lastId) {
if(err) throw err
callback(lastId);
});
}
pool.js
const util = require('util');
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: '**',
user: '**',
password: '**',
database: '***'
});
pool.getConnection((err, connection) => {
if(err)
{
console.error("Something went wrong connecting to the database.");
}
if(connection) {
connection.release();
}
return;
});
pool.query = util.promisify(pool.query);
module.exports = pool;

I think there's a few solutions you can try here.
In your pool.js file, just export pool.query and not the promisified version
Surround your call to pool.query in the create() function with a promise and resolve the promise with the lastId variable instead of using a callback
Use npm mysql2 as it comes with a promise wrapper: https://www.npmjs.com/package/mysql2#using-promise-wrapper
Hope that helps!

Related

How to handle promise handing error in mysql? (Debian, VMWARE)

So I am trying to use implement argon2 in my login application which uses a MySQL database. I have managed to store the username and its hashed password in the database while receiving a promise handling error. But I am unable to login with the same username and password by passing parameters via Postman since I get the same error.
Here is my code so far:
server.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("port", 8080);
const argon2 = require("argon2");
const Pool = require("mysql2").createPool;
const config = {
host: "localhost",
user: "root",
password: "XXXXX",
database: "XXXXX"
};
const pool = new Pool(config);
app.post("/login", async (req, res) => {
console.log(req.body);
const username = req.body.username;
const password = req.body.password;
try {
const query = "SELECT password from adminlogin where username = ?";
const result = await pool.query(query, [username]);
if (result.rowCount == 1) {
console.log(result.rows[0].password);
if (await argon2.verify(result.rows[0].password, password)) {
res.json("Log In successful");
} else {
res.json("Password incorrect");
}
} else {
res.json("username not found");
}
} catch (err) {
console.log("ERROR " + err);
}
});
app.post("/create", async (req, res) => {
let hash;
const username = req.body.username;
const password = req.body.password;
try {
hash = await argon2.hash(password, "abcdefghijklmnop");
console.log("HASH " + hash);
const query = "INSERT INTO adminlogin (username, password) VALUES (?, ?)";
const result = await pool.query(query, [username, hash]);
//console.log(result);
if (result.rowCount == 1) {
res.json("User created");
} else {
res.json("User not created");
}
} catch (err) {
console.log("ERROR " + err);
if (err.message.search("duplicate") != -1) {
res.json("Username taken");
}
}
});
Error Messages:
You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://www.npmjs.com/package/mysql2#using-promise-wrapper, or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md
ERROR Error: You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://www.npmjs.com/package/mysql2#using-promise-wrapper, or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md
The problem is you are using the MySQL npm package and it doesn't return any promises when you are using the pool.query(), it returns a callback. I have faced the same situation. Try to use it as a traditional callback function like pool.query(query, [username], (err, result)=>{}). and return the result as callback within that function. Hope this will be helpful for you.

How can I update data using NodeJS?

i want to update result prediction to database mysql, but data cannot save at database.
const periode = _.get(row, "periode", new Date());
const prediction =
b0 +
b1 * Number.parseFloat(_.get(row, "x1", 0)) +
b2 * Number.parseFloat(_.get(row, "x2", 0));
const sql = `UPDATE performance SET prediction_result="${prediction}" WHERE periode="${periode}"`;
db.query(sql, (error, results, fields) => {
if (error) {
console.error('An error occurred while executing the query')
throw error
}
})
i am getting error like this:
throw err; // Rethrow non-MySQL errors
ReferenceError: connection is not defined
Can you help me solve this problem?
You should have something like this in your code.
var mysql = require('mysql');
var db= mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

Nodejs mysql how to handle timeout and Handshake inactivity timeout

I am a newbie in Nodejs and I have a lambda function written on NodeJS that's supposed to delete some rows and insert some data on a mysql db.
I have come across various instances with error messages such as PROTOCOL_SEQUENCE_TIMEOUT, PROTOCOL_CONNECTION_LOST and an instance where the RDS db dns couldn't be resolved and connect to the db.
I was wondering how I might handle these events so I'd be able to re-connect and proceed.
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'somehost',
user : 'someuser',
password : 'somepassword',
database : 'somedb',
port : 3306
});
pool.on('connection', function (connection) {
console.log('Pool id %d connected', connection.threadId);
});
pool.on('enqueue', function () {
console.log('Waiting for available connection slot');
});
exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
let request = JSON.parse(event.body);
/** SOME OTHER LOGIC HERE **/
let delete_query = "DELETE FROM answers WHERE sId= ? AND `key` = ?";
pool.query(delete_query, [sId, questionId], function(err, result){
if(err) throw err;
});
let insert_query = "INSERT INTO answers (qId, sId, `key`, value, hutk) VALUES ?";
pool.query(insert_query, [values], function(err, result){
if(err) throw err;
console.log("Successfull Insert")
});
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify({message : 'success'}),
};
return response;
};
And also am I using the best approach to connecting to the db as in a pool or should I be using just a connection etc?
You can cache the connection, so the first call to your lambda would create the connection and the 2nd call (if the lambda is not cold started) can reuse the connection and is much faster.
Here is how we do it:
const mysql = require('mysql');
const util = require('util');
let mySQLconnection = undefined;
exports.handler = async function handler(event, context) {
try {
getMySQLConnection();
const queryResult = await mySQLconnection.query('Select * from yourtable where id = ? and attribute = ?', [id, attribute]);
} catch (error) {
console.log('ERROR: ' + error);
}
};
function getMySQLConnection() {
if (mySQLconnection !== undefined) {
return;
}
mySQLconnection = mysql.createConnection(yourConnectionJson);
mySQLconnection.query = util.promisify(mySQLconnection.query);
}
You could also do a connection retry in the catch block.

How to fix "err is not defined" error in Nodejs

I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
const express = require('express');
const mysql = require('mysql');
//Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'ca1903'
});
//Connect
db.connect(() => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
const app = express();
//create DB
app.get('/createdb', () => {
let sql = 'CREATE DATABASE ca1903';
db.query(sql, (err, result) => {
if(err){
console.log(err);
}
console.log(result);
res.send('database created....');
});
});
You were missing err parameter in the db.connect call. It should be in the below way.
// Connect
db.connect((err) => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});

Node.js with MySQL queries

I'm using MySQL for the first time, and I'm struggling to properly preparing statements and escaping query values. Here's where I'm at:
connection.connect();
formatDate(function(date){
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES ?";
var inserts = [req.param('name'), req.param('type'), date];
var queryString = mysql.format(sql, inserts);
console.log(queryString)
connection.query(queryString, function(err, results){
if(err) serverError(res, err);
else{
res.redirect('/view_coffee');
}
});
});
connection.end();
I'm using the 'mysql' node.js module by felixge.
You need a ? per value. Also, be sure to use a connection pool.
formatDate(function(date){
var sql = [
"INSERT INTO coffee_tbl SET",
" coffee_name=?",
",coffee_type=?",
",submission_date=?"
].join('');
var inserts = [req.param('name'), req.param('type'), date];
pool.getConnection(function(err, connection) {
if(err) return console.error(err);
connection.query(sql, inserts, function(err, results) {
connection.release();
if(err) return console.error(err);
res.redirect('/view_coffee');
});
});
});
To setup a connection pool:
var pool = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASS,
database: process.env.MYSQL_NAME,
connectionLimit: 8
});
Use environment variables for your mysql authentication information so as to not commit authentication information to a repo.
You only have one placeholder in your sql var, but you are trying to pass three values in your inserts var. You want to modify your sql var to have three placeholder like this:
var sql = "INSERT INTO coffee_tbl (coffee_name, coffee_type, submission_date) VALUES (?, ?, ?)";