Rares H.
Rares H.

Reputation: 102

Express response takes request method

I'm trying to make a Get response from a DELETE request

I'm using Ajax to make the DELETE, and currently using success to redirect.

$("#delete-account").click(function() {
    $.ajax({
        url: '/user',
        type: 'DELETE',
        success: function() {
            window.location='/user/new';
        },
        error: function(error) {
            console.log(error);
        }
    });
});

and in my Express route

router.delete('/', pass.isAuthenticated, function(req, res) {
    User.remove({_id: req.user._id}, function(err){
        if(err) return console.log(err);
        req.flash('success', 'Your account has been deleted.');

        res.redirect('/user/new');   <----------- this redirects to DELETE(/user/new)

    });
});

The redirect issues as DELETE response. I've tried setting req.method = 'get' and res.method = 'get' above. Neither work.

Any ideas ? :-/

Upvotes: 2

Views: 433

Answers (1)

Graham Coombe
Graham Coombe

Reputation: 60

Since this is an ajax call wouldn't you be better off making an additional call from the browser after the DELETE call concludes? Usually redirects are used to redirect the browser to a new url, but since this an ajax call the browser isn't being redirected anywhere.

If you need the server to tell where to redirect I would suggest having the response of the delete be something like:

router.delete('/', pass.isAuthenticated, function(req, res) {
   User.remove({_id: req.user._id}, function(err){
    if(err) return console.log(err);
    req.flash('success', 'Your account has been deleted.');

    res.send('/user/new');   <----------- Return location of new page

    });
});

And then your client would do:

$("#delete-account").click(function() {
  $.ajax({
    url: '/user',
    type: 'DELETE',
    success: function(data) {
        window.location=data;
    },
    error: function(error) {
        console.log(error);
    }
 });

});

Upvotes: 1

Related Questions