I’m making a simple node.js webapp for inserting data into a database with a condition – when there’s two instances with the same time attribute, the insert query isn’t called and you get redirected to a simple html page with a message that you have to pick another time.
My question is, how can I redirect from a block of code belonging to query? or is there another way to let user know that he has to pick another time?
JavaScript
x
24
24
1
app.post('/', function(req, resp) {
2
try {
3
var name = req.body.name;
4
var date = req.body.date + " " + req.body.time;
5
var phone = req.body.phone;
6
var spz = req.body.spz;
7
var typeOfProblem = req.body.typeOfProblem;
8
9
con.query(("SELECT COUNT(*) AS datecheck FROM `objednani` WHERE datetime = '"+ date +"'"), function(err, result){
10
if (err) throw err;
11
if(result[0].datecheck > 1){
12
console.log("preplneno"); // THIS IS THE POINT WHERE I WANT TO REDIRECT THE USER
13
} else {
14
con.query(("INSERT INTO objednani (name, datetime, phone, spz, typeofproblem) " + "VALUES ('"+name+"','"+date+"','"+phone+"','"+spz+"','"+typeOfProblem+"')"), function (err, result) {
15
if (err) throw err;
16
console.log("uspech");
17
});
18
}
19
});
20
} catch (err) {
21
resp.redirect('/fail');
22
}
23
});
24
Advertisement
Answer
You can call resp.redirect('/fail');
inside your query block, or anywhere in function(req, resp)
function. You don’t need to throw and catch.
As another suggestion: you can try parameter embedding for your sqls. otherwise you can be subject to sql injection attacks.