Reputation: 14780
I've looked at the following code:
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method;
delete req.body._method;
return method;
}
}));
in node-express-mongoose-demo repository and just interested what do the do? Does anybody could please explain me?
Upvotes: 0
Views: 230
Reputation: 12399
From the official documentation :
Method Override lets you use PUT and DELETE http methods. In this case, your app looks for a _method parameter to a POST query, and if it finds it, overrides the POST request for a 'delete', and removes the parameter from the body. In practice, you'd use it like this on the client :
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete resource</button>
</form>
Note the hidden input _method that will trigger your middleware's function.
Step by step :
if (req.body && typeof req.body === 'object' && '_method' in req.body) { //If we have a body, and it contains a _method field
var method = req.body._method; // Override the POST method with the value of the _method field (eg:DELETE in our example)
delete req.body._method; //remove the field from the body, we don't need it anymore
return method;
} //And our POST request is now a DELETE!
Upvotes: 1