代码之家  ›  专栏  ›  技术社区  ›  SilentDev

如何在post请求期间向req.body字典添加键值对

  •  0
  • SilentDev  · 技术社区  · 7 年前

    我正在使用NEDB和Express/Node。

    这是我的API:

    app.post('/api/texts/', function (req, res, next) {
    
        (req.body).push({
          key:   "additionalField",
          value: 0
        });
    
        texts.insert(req.body, function (err, text) {
            if (err) return res.status(500).end(err);
            return res.json(text);
        });
    });
    

    我正在尝试将自己的键添加到body字典中(我希望keys值为int)。

    当前的ODE给了我一个错误,说“typeerror:req.body.push不是函数”。

    1 回复  |  直到 7 年前
        1
  •  2
  •   dimitris tseggenes    7 年前

    你为什么不做一个新的东西?例如:

    app.post('/api/texts/', function (req, res, next) {
        const obj = {};
        for (let [key, value] of Object.entries(req.body)) {
            obj[key] = value;
        }
        obj.additionalField = 0;
    
    
        texts.insert(obj, function (err, text) {
            if (err) return res.status(500).end(err);
            return res.json(text);
        });
    });
    

    或者你可以简单地使用 req.body.additionalField = 0; 而不是创建新对象

    推荐文章