【问题标题】:How to drop request json properties in express js如何在 express js 中删除请求 json 属性
【发布时间】:2021-11-09 09:41:20
【问题描述】:

我对 express-js 还很陌生,所以这个问题可能看起来很傻,但是环顾四周,我找不到一个优雅的答案。

对于处理 post 或 put 方法的给定路由,我希望能够删除所有未指定的属性。例如,如果有一个创建 obj 的 post 请求为:

{  
title: "some title",
user: "some user",
body: "post body",
_id: "1332433242343",
}

我希望能够拥有一个只接受我需要的属性的中间件,例如:

(req, res, next) => {
   const { title, user, body } = req.body;
   clean_request = { title: title, user: user, body: body, };
}

原因是不是恶意代理,可以操纵内部数据库数据,因为_id属性是数据库的用户,它可以由请求者设置。

我正在使用 express-validate 来验证我的属性,但到目前为止,我还没有找到一种方法可以完全删除属性并只保留我需要的属性。

再次感谢您的任何建议。 ^^

【问题讨论】:

  • 您可以使用class-transformerclass-validatorclass-transformer 使用 excludeExtraneousValues 删除所有其他属性
  • 谢谢你,我希望我能把你的评论作为答案。

标签: javascript node.js express validation express-validator


【解决方案1】:

在一天结束时,我最终编写了自己的中间件,用于在 req 正文中删除不需要的属性:

allowed_properties = {
    username: true,
    lastname: true,
    firstname: true,
    condition: true,
    image: true,
    password: true,
    email: true,
 }

const cleanProperties = (req, res, next) => {
        /* clean the json of any unwanted properties */
        const clean_json = {}
        Object.keys(req.body).forEach(
                property => // for property
                allowedProperties[property] &&  // if is make as acceptable
                (clean_json[property] = req.body[property]) // pass to new obj
        );
        req.body = clean_json;
        next();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-04
    • 2013-10-28
    • 2013-02-25
    • 2019-11-04
    • 2012-02-03
    • 2022-07-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多