DELETE导致重定向循环?

时间:2014-08-25 16:06:40

标签: postgresql express

我有一个带有postgres后端的快速应用程序,用户可以在其中添加/删除食谱,每次这样做时,他们都会获得更新的食谱列表。添加配方很好,但是当我删除它时,它似乎陷入了重定向循环。在app.js我有

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

调用以下代码

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');
};

如果我尝试删除食谱,console.log('deleting')生成

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

recipes route位于下方(很遗憾,它很复杂)

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});
    });
  });
});

1 个答案:

答案 0 :(得分:1)

导致问题的一行是res.redirect('recipes');

首先,正如@Jordonias指出的那样,您应该将此行放在数据库查询的回调中。

其次,我认为该行会将您从YOUR_DOMAIN.COM/delete/:d重定向到YOUR_DOMAIN.COM/delete/recipes而不会重定向到YOUR_DOMAIN.COM/recipes,这会生成无限重定向循环。绝对与相对路径是一个非常常见的陷阱。

因此,您应该将代码更改为res.redirect('/recipes');