Send back rows and readstream in nodejs - mysql

Hey I would like to send back an image downloaded from s3 and data from MySQL database but i'm not sure if its even possible and if it is, how to do it.
Any help is welcome thanks!
app.get('/api/users/:id', (req, res) => {
var id = req.params.id;
pool.getConnection((err, connection) => {
if (err) throw err
console.log('connected as id ' + connection.threadId)
connection.query(`SELECT username, picture, DATE_FORMAT(creation_date, "%d %M %Y") as creation_date from users where idusers = ${id}`, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
const readStream = getFileStream(rows[0].picture);
readStream.pipe(res);
res.send(rows[0])
} else {
console.log(err)
}
})
});
})

Related

Validating data from mysql query in express.js

I have a post api which i want to validate data before inserting it into data base .
I want to check if the customerCode from the body exists in database or not .
this is my code but it always returns " Cannot read properties of undefined (reading '0')"
app.post('/CreateCustomer', (req, res) => {
pool.getConnection((err, connection) => {
if (err) throw err
const params = req.body
connection.query('SELECT CustomerCode FROM Customers WHERE CustomerCode = ?', params.CustomerCode, (err, rows) => {
// connection.release() // return the connection to pool
if (rows[0] == undefined) {
connection.query('INSERT INTO Customers SET ?', params, (err, rows) => {
connection.release() // return the connection to pool
if (!err) {
res.send(`Customers with the record ID has been added.`)
} else {
console.log(err)
}
console.log('The data from beer table are:11 \n', rows)
})
} else {
res.send("Csutomer Code Already taken!")
}
})
})
})

I can't Deploying Node.js app on Heroku with MySQL database

I need help on this one I'm stuck for three days... I need to deploy a node.js web app with MySql database to Heroku. Here what I`m done so far:
I succeeded to connect to heroku local on port 5000;
I succeeded to connect with the command heroku run node app.js;
I insert a proc file on the root directory :
Please help!
web: node app.js
But when I open the app from the heroku web site I have the following errors:
Here is my server file :
const express = require("express");
const exphbs = require("express-handlebars");
const bodyParser = require('body-parser');
const mysql = require('mysql');
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
// Parsing middleware
// Parse application/x-www-form-urlcoded
app.use(express.urlencoded({extended: true})); //New
app.use(express.json()); //To parse the incoming requests with JSON payloads
//to load static file
app.use(express.static("public"));
//Templating engine to change the extenion of file from .handlebar to .hbs
app.engine("hbs", exphbs({extname:".hbs"}));
app.set("view engine","hbs");
//Routes
const routes = require('./server/routes/user');
app.use("/",routes);
//Listen on port 5000
app.listen(port, () => console.log(`Listening on port ${port}`));
Here my app.js file
const mysql = require('mysql');
//Connection pool
let connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
// View Users
exports.view = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE status="active"', (err, rows) => {
//when done with the connection, release it
if (!err) {
let removedUser = req.query.removed;
res.render('home', { rows, removedUser });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
//find user by Search
exports.find = (req, res) => {
let searchTerm = req.body.search;
//User the connection
connection.query('SELECT * FROM user WHERE first_name LIKE ? OR last_name LIKE ?', ['%' + searchTerm + '%', '%' + searchTerm + '%'], (err, rows) => {
if (!err) {
res.render('home', { rows });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
exports.form = (req, res) => {
res.render('add-crew');
}
exports.create = (req, res) => {
const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;
let searchTerm = req.body.search;
//User the connection
connection.query('INSERT INTO user SET first_name = ?,last_name = ?,email = ?,phone = ?,coc=?,expiration=?,PSSR=?,FFB=?,ADV=?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV], (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
// edit crew function
exports.edit = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
if (!err) {
res.render('edit-crew', { rows });
} else {
console.log(err);
}
console.log('The data from uer table:\n', rows);
});
}
// Update crew
exports.update = (req, res) => {
const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;
connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, PSSR=?, FFB=?, ADV=? WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV, req.params.id], (err, rows) => {
if (!err) {
connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
//when done with the connection release it
// connection.release();
if (!err) {
res.render('edit-crew', { rows, alert: `${first_name} has been updated.` });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
//delete crew
exports.delete = (req, res) => {
// User the connection
connection.query('DELETE FROM user WHERE id = ?', [req.params.id], (err, rows) => {
if(!err) {
let removedUser = encodeURIComponent();
res.redirect('/?removed='+ removedUser);
} else {
console.log(err);
}
console.log('The data from user table: \n', rows);
});
}
// hide user
// connection.query('UPDATE user SET status = ? WHERE id = ?', ['removed', req.params.id], (err, rows) => {
// if (!err) {
// let removedUser = encodeURIComponent('User successeflly removed.');
// res.redirect('/?removed=' + removedUser);
// } else {
// console.log(err);
// }
// console.log('The data from beer table are: \n', rows);
// });
// }
exports.viewall = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id=?',[req.params.id], (err, rows) => {
//when done with the connection, release it
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
Here my package.json file:
{
"name": "nodejs-usermanagement",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-handlebars": "^5.3.2",
"mysql": "^2.18.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Here an update about the errors that are coming out after 10 minutes:

MySQL Node JS DELETE no working - 0 rows affected

I am trying to create a post route that will delete a user's data from several tables. I checked in mySQL workbench that the database user has this privilege. However when I click delete on the frontend, the queries appear to run but the rows do not get deleted. Can you someone please tell me where I am going wrong?
app.post('/disposal', redirectLogin, async(req, res) => {
const user = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
await connection.query(userStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(holdingsStmt, (err, results) => {
if (err) throw err;
console.log(results);
connection.query(cashStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
connection.query(tradesStmt, (err, results) => {
if (err) throw err;
console.log(results);
});
});
});
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})
I needed to change user = res.locals to { user } = res.locals as it the former was coming back 'undefined' as it was not properly extracting.
You don't need to nest the calls if you are using async/await.
As the res.locals is an object which contains the user property, you have to get the user property.
You could get it by using Object destructuring syntax.
Try this.
app.post('/disposal', redirectLogin, async (req, res) => {
const { user } = res.locals;
userStmt = `DELETE FROM users WHERE user_name ='${user.user_name}'`;
cashStmt = `DELETE FROM CASH WHERE user_name ='${user.user_name}'`;
tradesStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
holdingsStmt = `DELETE FROM trades WHERE user_name ='${user.user_name}'`;
try {
let results = await connection.query(userStmt);
console.log(results);
let holdinResult = await connection.query(holdingsStmt);
console.log(holdinResult);
let cashResult = await connection.query(cashStmt);
console.log(cashResult);
let tradesResult = await connection.query(tradesStmt);
console.log(tradesResult);
} catch (error) {
throw error
}
req.session.destroy(err => {
if (err) {
return res.redirect("/dashboard");
}
res.clearCookie(SESS_NAME);
res.send("Ninja disposed!");
})
})

express.js with MySQL

I just started learning node.js...
Here is an example of my code. In this example everything works.
But, I have a question. How to make several SQL queries and send results to template?
At the moment I can only do this for one query...
Thanks.
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'test'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
Here is an answer following my comment since you mentioned you couldn't figure it out on your own.
First snippet uses promises, a quick helper function, but no external library. Second snippet uses the external async.js library and is a bit more callback-heavy. Both of them tackle the problem assuming we want the queries to be executed in parallel.
With promises
router.get('/', async function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
/*transform our `query` array into an array of promises, then
await the parallel resolution of all the promises*/
var allQueryRows = await Promise.all(queries.map(query => promiseQuery(query)));
/*'allQueryRows' is an array of rows, so we push each of those
into our results*/
allQueryRows.forEach(function(rows){
allResults.push(...rows);
});
res.render('index', {
data: allResults
})
});
function promiseQuery(sqlQuery){
return new Promise((resolve, reject) => {
connection.query(sqlQuery, function(err, rows, field){
if(err)
return reject(err);
resolve(rows);
})
})
}
With callbacks and async.js
const async = require('async');
router.get('/', function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
async.each(queries, function(sqlQuery, callback){
connection.query(sqlQuery, function(err, rows, field){
if(err)
throw err;
allResults.push(...rows);
callback();
});
}, function(){
res.render('index', {
data: allResults
});
});
});

Express and mysql. rows are undefined

This is my code. I am writing API and I want to send information about products that client has input.
const express = require('express');
const mysql = require('mysql');
const morgan = require('morgan');
const app = express();
app.use(morgan('short'));
app.use(express.static('./public'));
// app.get('/', (req, res, next)=>{
// res.send('Hello World');
// });
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: 'root',
password:'samsung793',
database: 'demo2'
})
}
app.get('/models/:id', (req, res, next)=>{
console.log('Fetching id ' + req.params.id);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE id=?'
const modelId = req.params.id;
connection.query( queryStr, [modelId], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name) AGAINST(${req.params.name}, in natural language)`
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> <h3>Error!</h3> <h4>Sorry for error, we are working on it!</h4>');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
console.log(rows);
})
// res.end();
})
app.listen(3000, ()=>{
console.log('server is listening on port 3000');
} )
when I log to console the rows, it is undefined. How can I fix it? What is the problem?
Sorry for first post. I edit and add all code now. Please help me to solve this problem.
You need to check if any error occur while querying
app.get('/:name', (req, res, next) => {
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE MATCH(name) AGAINST(?, in natural language mode)';
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
console.log('Ready');
if(err) {
console.log(err);
return res.status(500).send(err);
}
console.log(rows);
res.json(rows);
})
})
If you are using prepared statement, you do not need to pass ${req.params.name}, just pass ?
Thank you for answers. I write code here in case someone needs it.
It works this way:
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name, url) AGAINST(? IN NATURAL LANGUAGE MODE) `
const modelName = req.params.name;
connection.query( queryStr, modelName, (err, rows, fields)=>{
console.log(rows);
if (err){
res.status(404).send(" Something went wrong");
// res.sendStatus(500);
throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})