Is there a way to simplify this code in 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 petition with an advantage.
So my question is: do I have to do this in every post handler, or is there a way of filtering properties?
Is there a way to simplify this code in 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 petition with an advantage.
So my question is: do I have to do this in every post handler, or is there a way of filtering properties?
Share edited Apr 17, 2018 at 6:00 Mick 6,8744 gold badges54 silver badges71 bronze badges asked Jan 19, 2015 at 6:50 javorosasjavorosas 7691 gold badge12 silver badges22 bronze badges1 Answer
Reset to default 8A quick Google search didn't find any pre-existing libraries, but this function should do the trick quite nicely:
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"]);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745049658a4608307.html
评论列表(0条)