【问题标题】:Filter body of a post request in node.js在 node.js 中过滤发布请求的正文
【发布时间】:2015-03-17 03:26:22
【问题描述】:

有没有办法在 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 属性并以优势开始竞争。

所以我的问题是:我必须在每个 post 处理程序中都这样做,还是有过滤属性的方法?

【问题讨论】:

    标签: javascript node.js api security express


    【解决方案1】:

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

    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"]);
    

    【讨论】:

    • 优秀。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多