Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS - res.redirect after DELETE request

I have been searching all over for how to do this - I am trying to redirect after a DELETE request is made - here is the code I am using WITHOUT THE REDIRECT:

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

remove gets called when an item (a post) is deleted. Everything works fine (I had to use res.send(200) to get it to not hang on the delete request) - but now I am having trouble redirecting. If I use res.redirect('/forum') inside the remove function, like this:

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

It registers the redirect as a DELETE request that is trying to delete /forum, like this:

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

All I am trying to do is refresh the page so that the list of posts is updated after the delete. Can anyone help?

like image 778
ewizard Avatar asked Jul 15 '14 05:07

ewizard


2 Answers

I got it working on my Angular side with $window.location.href = '/forum'; - just put it in the success function of the $http request that is part of the delete function that gets executed when the "Delete" button is clicked.

like image 163
ewizard Avatar answered Sep 19 '22 12:09

ewizard


@ewizard 's solution is great if you can fix this on the front end. However, if you want to fix this on the back end, you can add an optional Status Code argument to res.redirect like so:

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

This redirects for "Undefined Reason" which will default to a GET redirect.

See this SO post for more info.

like image 22
ZebGir Avatar answered Sep 21 '22 12:09

ZebGir