0

So the thing is that I'm trying to catch a MySQL error, so when it happens I just want to redirect the user to another page of my app and display a notification or something, but doesn't matter what URL I put in the redirect method it sends me to the index page "/". This is my code, as you can see I even put Google URL, but it stills send me to home "/".

var query = "DELETE FROM buildings WHERE id = ?";
connection.query(query, id, function(err) {
    if (err) {
        console.log("Foreign key restriction");
        return res.redirect("http://google.com");
    }
    if (fs.existsSync('./public/' + img)) {
        fs.unlinkSync('./public/' + img);
    }
    res.redirect("/");
});

Also is good to say that the "Foreign key restriction" is printed on console, but I'm not redirected. Any thoughts? Thank you!

erosespinola
  • 103
  • 8

2 Answers2

1

err never gets set so you always fallback and the last redirect to / is used.

You are missing a [] in your query call. I.e., it should be

connection.query(query, [id], function(err) {
nimrodm
  • 23,081
  • 7
  • 58
  • 59
  • Actually I made a console.log inside the if(err) and it gets there, I tried connection.query(query, [id], function(err) but it still doesn't work :/ – erosespinola Dec 14 '14 at 04:30
  • if (err) { console.log("lol"); //this is actually printed in console return res.redirect("http://google.com"); } – erosespinola Dec 14 '14 at 04:34
0

Make sure that you are "returning" to the correct function. As in try to return your query first as so:

return connection.query(query, id, function(err) {

Mass010
  • 11
  • 3
  • said in other words... the returning should be bubbled up all the way to the route/function using 'res' as an argument. i hope this works for you buddy! – Mass010 Dec 14 '14 at 05:20