Reputation: 59485
Below I have a post request which a user can make and if the hidden form item with the name _method
is deleted it will make a request to my own server to a different route and delete the post from the database. How should this process work?
app.post("/posts/:id/delete", function(req, res){
if(req.body._method = "delete"){
request({
"method": "delete",
"url": "/posts/"+req.param.id
}, function(err, response, body){
res.redirect("/posts");
});
}
});
app.delete("/posts/:id", function(req, res){
//delete it from the database
res.redirect("/posts");
});
Upvotes: 1
Views: 260
Reputation: 123533
Assuming Express/Connect, methodOverride()
is probably the simplest option:
app.use(express.bodyParser());
app.use(express.methodOverride());
Though, the <form action>
and route path
should match:
<form action="/posts/{{id}}" method="post">
<input type="_method" value="delete" />
<!-- ... -->
</form>
app.delete('/posts/:id', function (req, res) {
//delete it from the database
res.redirect("/posts");
});
[Update] With Express 4 and newer, this middleware has moved to method-override
.
Upvotes: 1