gpt4 book ai didi

javascript - node.js 中 post 请求的过滤体

转载 作者:搜寻专家 更新时间:2023-11-01 00:14:56 25 4
gpt4 key购买 nike

有没有办法在 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(...);
});

我没有这样做:

    var participant = new Participant(data);

因为任何人都可以在数据对象中包含(例如)score 属性并以优势开始比赛。

所以我的问题是:我是否必须在每个帖子处理程序中执行此操作,还是有过滤属性的方法?

最佳答案

Google 快速搜索没有找到任何预先存在的库,但这个函数应该可以很好地解决问题:

function filterKeys(object, keys) {
Object.keys(object).forEach(function(key) {
if(keys.indexOf(key) == -1) {
delete object[key];
}
});
}

举个例子,

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}

所以在你的情况下,

filterKeys(data, ["first", "last", "email", "category"]);

关于javascript - node.js 中 post 请求的过滤体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28019289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com