ExpressJS - DELETE请求后的res.redirect

ewi*_*ard 12 javascript redirect request express http-delete

我一直在搜索如何执行此操作 - 我在尝试DELETE请求后重定向 - 这是我正在使用的代码没有重定向:

exports.remove = function(req, res) {
  var postId = req.params.id;
  Post.remove({ _id: postId }, function(err) {
    if (!err) {
            console.log('notification!');
            res.send(200);
    }
    else {
            console.log('error in the remove function');
            res.send(400);
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

remove在删除项目(帖子)时调用.一切正常(我不得不使用res.send(200)它来挂起删除请求) - 但现在我无法重定向.如果我res.redirect('/forum')remove函数内部使用,像这样:

exports.remove = function(req, res) {
  var postId = req.params.id;
  Post.remove({ _id: postId }, function(err) {
    if (!err) {
            console.log('notification!');
            res.send(200);
    }
    else {
            console.log('error in the remove function');
            res.send(400);
    }
    res.redirect('/forum');
  });
};
Run Code Online (Sandbox Code Playgroud)

它将重定向注册DELETE为尝试删除的请求/forum,如下所示:

DELETE http://localhost:9000/forum 404 Not Found 4ms

我要做的就是刷新页面,以便在删除后更新帖子列表.有人可以帮忙吗?

小智 7

我知道这已经晚了,但是对于以后看到此内容的任何人,您还可以手动将 HTTP 方法重置为 GET,这也应该有效

exports.remove = function(req, res) {
  var postId = req.params.id;
  Post.remove({ _id: postId }, function(err) {
    if (!err) {
            console.log('notification!');
            res.send(200);
    }
    else {
            console.log('error in the remove function');
            res.send(400);
    }

    //Set HTTP method to GET
    req.method = 'GET'

    res.redirect('/forum');
  });
};
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您可以在前端修复此问题,@ewizard 的解决方案就很棒。但是,如果您想在后端修复此问题,您可以添加一个可选的状态代码参数,res.redirect如下所示:

res.redirect(303, "/forum");

此重定向针对“未定义原因”,默认为 GET 重定向。

请参阅此帖子以获取更多信息。


ewi*_*ard 3

我让它在我的 Angular 端工作$window.location.href = '/forum';- 只需将它放在请求的成功函数中,该请求是单击“删除”按钮时执行的函数的$http一部分。delete