DELETE causing a redirect loop?

Posted by robocode on Stack Overflow See other posts from Stack Overflow or by robocode
Published on 2014-08-25T16:06:40Z Indexed on 2014/08/25 16:20 UTC
Read the original article Hit count: 227

Filed under:
|

I have an express app with a postgres backend where a user can add/delete recipes, and each time they do so they get an updated list of recipes. Adding a recipe is fine, but when I delete one it seems to get stuck in a redirect loop. In app.js I have

router.get('/delete/:d', delRec.deleteRecipe);

which calls the following code

exports.deleteRecipe = function(req, res){
  pg.connect(conString, function(err, client) {
    client.query('DELETE FROM recipes WHERE recipe_name = ', [req.params.d], function(err, result) {
      if(err) {
        return console.error('error running query', err);
      } else if (result) {
        pg.end();
        console.log('deleting');
      }
    });
  });
  res.redirect('recipes');
};

If I try delete a recipe, console.log('deleting') produces

deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting
deleting

The recipes route is below (sorry that it's so convoluted)

router.get('/recipes', function(req, res) {
  pg.connect(conString, function(err, client) {
    if(err) {
      return console.error('could not connect to postgres', err);
    }
    client.query('SELECT * FROM recipes', function(err, result) {
      if(err) {
        return console.error('error running query', err);
      }
      recipes = result.rows;

      for(var d in recipes) {
        if (recipes.hasOwnProperty(d)) {
          recipeList[d] = recipes[d].recipe_name;
        }
      }
      res.render('recipes', {recipes: recipes, recipeList: recipeList});
    });
  });
});

© Stack Overflow or respective owner

Related posts about postgresql

Related posts about express