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)
});
Related
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 :)
i have created one dropdown that passes data to NodeJS through axios post i can see that in console log of nodejs Post but cant able to use the value outside the post function
i want to use the value to querying the database
my nodejs code:
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here but can't able to use outside
});
app.get('/model', (req,res)=>{
let model = req.body.model;
let sql ="select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql,model, (err,results) =>{
if(err){
throw err
}
console.log(results)
res.send(results);
})
})
my react code works fine as i can able to see the selected value in nodejs console below
these are the selected value from my dropdown that shows in my nodejs console. but in cant use it by req.body like that please help me
You can try like this
app.post('/getmodel', (req, res) => {
var model = req.body.model;
console.log(model);
//It shows model value here and you can able to use in the query
let sql = "select * from new_schema.model_list,new_schema.images where model_name= " + mysql.escape(model)
db.query(sql, model, (err, results) => {
if (err) {
throw err
}
console.log(results)
res.send(results);
})
});
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?
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);
}
});
I'm building a web site using node.js express MySQL and boostrap, when I try to send a variable against method get for to do a query to the database, it's seem doesn't work, because there's no a good render. this is my code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
crud.get_leer_reservacion(req,idreservacion,function(data_leer){
res.render'../views/leer.html',data:data_leer});
});
});
exports.get_leer_reservacion = function(req,idreservacion,fn){
// here the query
connection.query('select * from reservacion where idreservacion = '"+idreservacion+"'', function(err,rows){
if(err){
throw err;
}
return fn(rows);
});
};
https://drive.google.com/folderview?id=0BxFTEy90zOKAfmJOXzR3NDFLa081NUtEUFU4LWhuN2ZUTDMtVktPeHlYbVUzWW02a2pGWEk&usp=sharing
res.render'../views/leer.html',data:data_leer});
should be:
(outside of app.get:)
app.use('views', '../views');
(inside:)
res.render('leer',{data:data_leer});
If your problem is actually getting the templated data into the page I suggest the ejs npm package and templating system, you would use <%= data => to template in the value
In this code:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.idreservacion;
You define a parameter called id, but you retrieve a parameter called idreservacion. Try something like this:
app.get('/reservaciones/leer/:id', function(req, res) {
var idreservacion = req.params.id;