我查看了以下代码:
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;
}
}));
在node-express-mongoose-demo存储库中,只是感兴趣的是做什么的?有人可以解释一下吗?
答案 0 :(得分:1)
来自官方文件:
Method Override允许您使用PUT和DELETE http方法。在这种情况下,您的应用程序会查找POST查询的_method参数,如果找到它,则会覆盖POST请求以进行“删除”,并从正文中删除该参数。在实践中,您可以在客户端上使用它:
<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>
请注意隐藏的输入_method,它将触发您的中间件功能。
一步一步:
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!