[英]Filter body of a post request in node.js
Is there a way to simplify this code in node.js + express? 有没有办法在node.js + express中简化这段代码?
// Backend handler to register a new participant
app.post('/api/participant', function (req, res, next) {
// I'm catching the registration form from the request
var data = req.body;
// I want to make sure the user is not uploading data other
// than the fields in the form
var participant = new Participant({
first: data.first,
last: data.last,
email: data.email,
category: data.category
});
participant.save(...);
});
I did not do this: 我没有这样做:
var participant = new Participant(data);
Because anyone could include (for example) a score
property in the data object and start the competition with an advantage. 因为任何人都可以(例如)在数据对象中包含一个
score
属性,并利用竞争优势开始竞争。
So my question is: do I have to do this in every post handler, or is there a way of filtering properties? 所以我的问题是:我必须在每个后处理程序中执行此操作,还是有一种过滤属性的方法?
A quick Google search didn't find any pre-existing libraries, but this function should do the trick quite nicely: 快速的Google搜索未找到任何预先存在的库,但是此功能可以很好地完成此工作:
function filterKeys(object, keys) {
Object.keys(object).forEach(function(key) {
if(keys.indexOf(key) == -1) {
delete object[key];
}
});
}
As an example, 举个例子,
var foo = {"foo": 1, "bar": 2, "baz": 3};
console.log(foo); // {"foo": 1, "bar": 2, "baz": 3}
filterKeys(foo, ["foo", "baz"]);
console.log(foo); // {"foo": 1, "baz": 3}
So in your case, 所以在你的情况下,
filterKeys(data, ["first", "last", "email", "category"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.