ExpressJS - Send variable as response on POST request - mysql

I am trying to retrieve insertId of the SQL and send it back to the front end. But when I do the res.send(result.insertId), I am getting a 500 Error. How can I deliver the insertId of the sql to the front end successfully?
router.post('/list', function(req, res, next) {
var lastIncrement = 0;
pool.getConnection(function (error, connection) {
connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
if(error)
console.error(error);
lastIncrement = result.insertId;
connection.release();
});
});
res.send(lastIncrement);
});

There is one problem in your code for sure that you are returning before finishing the query. So you have to return from inside the callback function.
router.post('/list', function(req, res, next) {
var lastIncrement = 0;
pool.getConnection(function (error, connection) {
connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
if(error)
console.error(error);
lastIncrement = result.insertId;
connection.release();
res.send(lastIncrement);
});
});
});

Due to asynchronous nature of nodejs your res.send is executing before the query returns the value. You can use a .then promise to ensure that the res.send happens after you get the value from query or have res.send after assigning the value.
You can try this:
pool.getConnection(function (error, connection) {
connection.query('INSERT INTO test_table SET Name = ?, Age = ?', [req.body.Name, req.body.Age], function (error, result) {
if(error)
console.error(error);
lastIncrement = result.insertId;
connection.release();
}).then(function(){
res.send(lastIncrement);
})
});

Related

Calling mysql queries dependent on another query in node

can anyone help me.
I need to get result of queryA [which is an update query that returns ROW_COUNT( )], see if the result is equal to 1.
If not, just return it via res.json
If yes, call queryB [which returns a set of rows].
After which, I have to loop and call queryC to update each row. It has to be one at a time because the queryC is also inserting auditTrails within the stored procedure.
This is the source code:
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*GET rows to be updated*/
const GetRows = connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE rows*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
if (error) {
return console.error(error.message);
}
});
});
});
}
res.json(updateCus);
connection.end();
});
Error:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Query'
then another one at the bottom:
throw er; //Unhandled 'error' event
You are missing 'await' before the mysql.createConnection(config) and connection.query call, since these are asynchronous functions. Also in your code connection.end() should be inside the callback.
exports.migrateCustomer = asyncHandler(async (req, res) => {
const { oldCustomerID, newCustomerID, userID } = req.body;
const connection = await mysql.createConnection(config);
let sql = `CALL usp_UpdateCustomerCallStatusIdAndIsActive(?,?,?)`;
/*UPDATE Customer*/
const updateCus = await connection.query(sql, [oldCustomerID, 'Duplicate', userID], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
return results[0];
});
if (updateCus.rowCount == 1) {
let sql = `CALL usp_GetPurchaseOrderByCustomerIDAndNameSearch(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [oldCustomerID, ''], (error, results, fields) => {
if (error) {
connection.end();
return console.error(error.message);
}
results[0].forEach(element => {
let sql = `CALL usp_UpdatePurchaseOrderByCustomerID(?,?)`;
/*UPDATE Customer*/
connection.query(sql, [newCustomerID, userID], (error, results, fields) => {
connection.end();
if (error) {
return console.error(error.message);
}
});
});
});
}else{
connection.end();
return res.status(200).json({
customer:updateCus});
}
});

Do not wait for mysql database result in node js

I tried to get result using mysql database query from called function but do not wait for result in called function. Following is my code for users.js file. I got result in getBankDetail function but do not get result in users function.
var db = require("../db/mysqlconnection");
function users(app){
app.get("/users",async function(req, res, next){
let bankDetail = await getBankDetail();
console.log("bankDetail",bankDetail); //Here I do not got result
return res.send(bankDetail);
});
}
async function getBankDetail(){
db.getConnection(async function(err, connection) {
if (err) throw err; // not connected!
await connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) throw error;
console.log("bank result",results); //Here I got result
return results;
});
});
}
module.exports = users;
My Question is why do not wait for result in called function? I also used async/await functionality.
function getBankDetail(){
return new Promise((resolve, reject) => {
db.getConnection(function(err, connection) {
if (err) reject(err); // not connected!
connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) reject(err);
console.log("bank result",results); //Here I got result
resolve(results);
});
});
});
}
And then you can use let bankDetail = await getBankDetail();
If you want to use await on your db.getConnection and connection.query you will have to use mysql2/promises library or promisify those functions yourself
Here is the implementation when you use the promisified version of your database driver:
async function getBankDetail(){
const connection = await db.getConnection();
const data = await connection.query('SELECT * FROM bank');
connection.release();
console.log("bank result", data[0]); //Here I got result
return data[0];
}

Node.js - Express & mysql TypeError: res.json is not a function although insert is successful

Although I have a successful insert I get an error (TypeError: res.json is not a function) when I want to return a json message upon. This is my setup:
const express = require('express');
module.exports = {
signup: async (req, res, next) => {
const { email, username, password } = req.value.body;
const connection = require('../config/dbconnection');
connection.query("SELECT * FROM tbl_users WHERE email = ?",[email], function(err, rows) {
if (rows.length) {
return res.json({ err: 'Email already exist'});
} else {
var newUserMysql = {
email: email,
username: username,
password: password
};
var insertQuery = "INSERT INTO tbl_users ( email, username, password ) values (?,?,?)";
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, res, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
}
});
}
How can I return a json on successfull insert?
Your function's res parameter is hidden by the res return value from the connection.query call.
Rename the res parameter of this call to result (for example) and you should be fine:
connection.query(insertQuery,[newUserMysql.email, newUserMysql.username, newUserMysql.password],function(err, result, rows) {
if(err){
console.log('Insert error');
//res.json({ err: 'Insert error'});
} else {
console.log('Insert successful');
return res.json({ 'success': 'Insert successful'});
//return done(null, newUserMysql);
}
});
When you have nested scopes with conflicting variable names, the variable the closest (scope-wise) from where you reference this conflicting name will be used.
You're redefining res in your connection.query(insertQuery, [.....], function(err, res, rows) { ...}) function.
That res overrules the res from your express router within the scope of that function

Trying to return a row from MySql using a function inside a route and won't get a response

So i'm trying to use a function that returns a row from a mySql database inside my route here:
.get('/users', function (req, res){
res.send(userInfo(req.user.id));
})
Here is the function:
function userInfo(id){
colDB.query('SELECT username FROM users WHERE id = ?', [id], function(err, rows){
if (err)
return {Error: defErrorMsg};
else
return rows;
})}
I'm fairly new to node and I can't figure out why isn't this working. Please help :(
I think this is to do with the callback nature of node. You are returning the value before it exists (treating async code like it's synchronous). Try the following:
function userInfo(id, callback){
colDB.query('SELECT username FROM users WHERE id = ?', [id], function(err, rows){
if (err)
callback(err, null);
else
callback(null, rows);
})}
And then change the route to look like this:
.get('/users', function (req, res){
userInfo(req.user.id, function(err, user){
if(err) return res.send(err)
res.send(user)
});
})

Nodejs with Mysql Database Return value

I have the following code. I am relative new to nodejs &js
I want to get values in 1. log but i get undefined.
Only 2. log is outputed to the log.
I read nodeJS return value from callback and
https://github.com/felixge/node-mysql but there is no example about return value.
I donot know how to use return statement with the given example in node-mysql page.
exports.location_internal = function (req, res) {
var r = getExternalLocation(2);
// 1. log
console.log(r);
res.send( r);
}
var getExternalLocation = function (id) {
pool.getConnection(function(err, connection){
if(err) throw err;
var response = {};
connection.query( "select * from external_geo_units where geo_unit_id = "+id, function(err, rows){
if(err) throw err;
response.data= rows;
// 2. log
console.log(response);
return response;
});
connection.release();
});
};
It's asynchronous, so you have to pass in a callback to get the value when it's ready. Example:
exports.location_internal = function(req, res, next) {
getExternalLocation(2, function(err, rows) {
if (err)
return next(err);
console.log(rows);
res.send(rows);
});
};
function getExternalLocation(id, cb) {
pool.getConnection(function(err, conn) {
if (err)
return cb(err);
conn.query("select * from external_geo_units where geo_unit_id = ?",
[id],
function(err, rows) {
conn.release();
cb(err, rows);
});
});
}