简体   繁体   English

自定义 req.body Nodejs

[英]Customize req.body Nodejs

I want to know, is it possible to make custom req.body which is will be send to MongoDB.我想知道,是否可以制作将发送到 MongoDB 的自定义 req.body。 In my case, I have req.body like this :就我而言,我有这样的 req.body :
{ f_name: 'John', l_name: 'Doe', phone: '4521234892345' }
But, what i expected is :但是,我期望的是:

{
 "f_name": {
  "type": "text",
  "value": "John"
 },
 "l_name": {
  "type": "text",
  "value": "Doe"
 },
 "phone": {
  "type": "number",
  "value": "212348923"
 }
}

The value of type are coming from HTML <input /> in a form. type的值来自表单中的 HTML <input />
For example :例如 :
<input type="text" name="f_name" value="John">
and
<input type="number" name="phone" value="212348923">
My backend :我的后端:

app.post("/api/leads/:userId/:formId", async (req, res) => {
  console.log(req.body);
});

My other backend:我的另一个后端:

app.get("/view/:id", async (req, res) => {
    const result = await Form.findOne({ _id: req.params.id });
    // console.log(result);
    // console.log(err)
    const data = JSON.parse(JSON.stringify(result));
    res.render("form", {
     data
    });
});

My Frontend(form.pug) :我的前端(form.pug):

    form(action='/api/leads/'+data._user+'/'+data._id, method='POST')
      mixin FieldGroup(id, type, label, text)
        div(classname="field-group")
          .field-group__inner
            if label
              label(classname="capitalize")= text
              |  :
              .field-row__inner
                input(id=id classname="input input--text" type=type name=text.toLowerCase().split(' ').join('_'))
            else
              .field-row__inner
                input(id=id classname="input input--text" name=text.toLowerCase().split(' ').join('_') type=type placeholder=text)
      each val, index in data.formElement.fieldRows
        .field-row 
          .field-row__inner
            each fieldGroup, i in val.fieldGroups
              +FieldGroup(fieldGroup.id, fieldGroup.type, fieldGroup.useLabel, fieldGroup.labelPlaceholder)
      .is-center.m-top-30
        button.button.is-success(type='submit') Submit

I mean, if you have control of the front end, just make your form mirror your data model.我的意思是,如果您可以控制前端,只需让您的表单反映您的数据模型。 Otherwise, transform you data at your server before it makes a call to your database.否则,在您的服务器调用您的数据库之前转换您的数据。 It's what we all have to do.这是我们所有人都必须做的。

Your HTML in a form.表单中的 HTML。 Like :喜欢 :

<input type="hidden" name="f_name[type]" value="text">
<input type="text" name="f_name[value]" value="John">

and in your app.js body-parser extended should be true like并且在你的 app.js body-parser 中扩展应该是真的

bodyParser.urlencoded({ extended: true });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM