jav*_*sas 2 javascript security api 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(...);
});
Run Code Online (Sandbox Code Playgroud)
我没有这样做:
var participant = new Participant(data);
Run Code Online (Sandbox Code Playgroud)
因为任何人都可以score在数据对象中包含(例如)属性并以优势开始竞争.
所以我的问题是:我是否必须在每个帖子处理程序中执行此操作,或者是否有过滤属性的方法?
一个快速的谷歌搜索没有找到任何预先存在的库,但这个功能应该很好地完成这个技巧:
function filterKeys(object, keys) {
Object.keys(object).forEach(function(key) {
if(keys.indexOf(key) == -1) {
delete object[key];
}
});
}
Run Code Online (Sandbox Code Playgroud)
举个例子,
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}
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,
filterKeys(data, ["first", "last", "email", "category"]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1198 次 |
| 最近记录: |