1

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");
});
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

1 Answers1

1

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.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199