erosespinola
erosespinola

Reputation: 113

Express and Node js - Can't redirect on error

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!

Upvotes: 0

Views: 258

Answers (2)

Mass010
Mass010

Reputation: 11

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) {

Upvotes: 0

nimrodm
nimrodm

Reputation: 23839

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) {

Upvotes: 1

Related Questions