Node.js: make a delete request with link
I'm trying to send a DELETE request with a link so that I can use express.js routing after it
<md-button href="/delete/{{userId}}">Delete</md-button>
app.delete('/delete/:user_id', function(req, res) {
User.remove({
_id : req.params.user_id
}, function(err, user) {
if (err)
res.send(err);
res.redirect('/');
});
});
Note: the md button comes from https://material.angularjs.org and the href attribute behaves like an anchor tag.
However, this throws an error:
Cannot GET /remove/5536d672106a3b540e0b0d96
Is it possible to change the default behavior for links to make a DELETE request instead of a GET, or the only way to make an AJAX call and route elsewhere?
source to share
yes you will need to make an ajax call where the method is DELETE
. clicking on the link will always execute a get request unless you intercept it, unless javascript does something else preventDefault()
on the event as well.
since you are using angular you can do something like this:
<md-button ng-click="vm.deleteUser(userId)">Delete</md-button>
and in your controller (which you linked as "vm" for this example to work), you can have
this.deleteUser = function(userId){
... using your favorite lib do the delete request at '/delete/'+userId
}
source to share