MySQL query works with POST but not with GET (Node/Express) - mysql

POST works but GET doesn't work.
This works:
app.post('/POSTexample', function(req, res) {
connection.query('SELECT * FROM users WHERE username = ?', req.session.username, function(error, results, fields) {
#using query results
response.redirect('/account');
});
res.redirect('/account');
});
But this doesn't work (gets stuck and never loads):
app.get('/GETexample', function(req, res) {
connection.query('SELECT * FROM users WHERE username = ?', req.session.username, function(error, results, fields) {
#using query results
});
res.redirect('/account');
});
What are the possible solutions to this issue?

Put your res.redirect() calls in the callback function from your MySql queries. The way you have it, you're redirecting before the queries complete.
asynchronous coding takes some getting used to, doesn't it?

Related

Node.JS - SQL Injection in URL parameters?

I'm trying to learn Node.js and I'm currently making an Express app (using ejs) that will return values from a MySQL database, depending on the URL the user visits.
For example, visiting http://localhost:3000/test will list all users from the db table users. And the link http://localhost:3000/test/3 will return information about the user with the id number 3.
My code for: /test
app.get("/test", (req, res) => {
let sql = "SELECT * FROM users ORDER BY name";
db.query(sql, function (err, results, fields) {
if (err)
logmessage(err.message);
res.render("test", { data: results });
});
});
And here is the code for /test/:id
app.get("/test/:id", (req, res) => {
var userId = req.params.id;
let sql = "SELECT * FROM users WHERE id = " + userId;
db.query(sql, function (err, results, fields) {
if (err || !results.length) {
res.redirect("/");
} else {
res.render("test_user", { data: results });
}
});
});
My question is: is this safe? When I previously worked in PHP development, I used to prepare statements before making any queries.
What happens if a user changes the URL from: http://localhost:3000/test/3 and inserts some SQL injection code at the end of the url? Can the database be breached?
This will be for a live app on the web, so it's important no SQL injection can be made. I also want to add a form later on (req.body instead of req.params) that I also need to sanitize.
Or is there a built-in "prepared statement" already in Node?
SQL injection is prevented if you use placeholders:
let sql = "SELECT * FROM users WHERE id = ?";
db.query(sql, [userId], function (err, results, fields) {...});
Have you tried to implement Sequelize? From what I read ORMs prevent SQL injection. Also, it's pretty easy to use :)

Node Express MySQL multiple routing

I want to make an route with multiple parameters using Node Express MySQL. Is it possible to do this with traditional url parameters like: page?id=2&user=10
Here is a simple query, but the only way of doing it so far is like this: page/2/10
app.get("/get-page/:id/:user", function (req, res) {
let sql = "SELECT * FROM table WHERE id= '${req.params.id}' AND userid= '${req.params.user}'`;";
let query = db.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
});
This is just an example.
The reason I would like the traditional way is because, with the "slash" method the parameters always have to come in the correct order, or did I miss something?
Perhaps use the query property of the request to access the query string, as in req.query.id:
app.get("/get-page", function (req, res) {
console.log('ID: ' + req.query.id)
});

nodejs throws error with mysql like query via prepared statements

Am retrieving values from database using nodejs.
I implemented mysql like query via prepared statement to ensure that sql injection attack is eliminated. my problem is that it does not retrieve any result. it just show empty results in the console please can someone point to me what is wrong with the query
exports.autosearch = function (req, res) {
//var search = req.body.searchText;
var search = 'bukatti';
//db.query('SELECT * FROM users WHERE name like ?', ['%' + search + '%'], function (error, results, fields) {
db.query('SELECT * FROM users WHERE name like ?', ['%search%'], function (error, results, fields) {
console.log(results);
});
}
Thanks
I have found out my problem. i added the error log and discover that the was type error somewhere. This fix it anyway
db.query("SELECT * FROM users WHERE name like ?", ['%' + search + '%'], function (error, results, fields) {
Thanks

how do I access the result(object) of a get request using express?

Here is my get request made to a mysql table
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
console.log(results);
}
});
res.render('index');
});
As it stands, this function allows me to grab the information I want from the table and I can read the results via console.log. However, I'm unable to access results on my index.ejs page.
How do I access results(which is an object that contains the stuff I want) in my index.ejs file? Whenever I try to access results, it says that results in undefined. How do I make sure that the object that is created as a result of the call to the table is able to be used/accessed on a different page. For the time being, I would just like to create a simple table that has the keys in one column and the values in a second column.
You need to modify your code as below. The reason is db.query is an async operation and you are trying to render before the async request completed. Also, to be able to reach the result at your template engine, you need to pass the results to the render. (index.ejs)
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
res.render('index', results);
console.log(results);
}
});

How to do a query to mysql database AFTER client`s request in nodejs/socket.io?

All examples i've seen were doing a query first and then send to client some info.
If I do a query FIRST and then use results in functions it works:
client.query(
('SELECT * FROM '+TABLES_USERS),
function(err, results, fields) {
var Users = (results);
io.sockets.on('connection', function (socket) {
socket.on('event1', function (data) {
var requser = Users[data];
socket.emit('event2', requser);
});
});
client.end();
});
But now i need to do a query on client's request.
I tried something like this but query doesn't work:
io.sockets.on('connection', function (socket) {
socket.on('event1', function (data) {
console.log('query required'); /*works*/
client.query(
('SELECT * FROM '+TABLES_USERS+' WHERE id_user ='+data),
function(err, results, fields) {
if (err) {throw err; /*doesn't work*/
console.log('error'); /*doesn't work*/ }
console.log('query is done'); /*doesn't work too. so i think query just doesn't work cuz there are no error and no results*/
socket.emit('event2', results);
client.end();
});
});
});
There are some things you are not doing ok (in my opinion) in the example above:
1) You don't ask for login after the client is connected to Socket.IO, instead you check to see if his session contains data that can verify is he's connected.
You should read the article about Express, Socket.IO and sessions., since it explains everything in detail (if you are using Express)
2) I think MongoDB, CouchDB and possibly other databases are better suited for realtime applications than MySQL.
I've solved the problem by using node-mysql-libmysqlclient instead of node-mysql. But if someone knows a way to do a query AFTER client's request in node-mysql, please tell me))