【问题标题】:Can not read data from express form ( return null)无法从 express 表单中读取数据(返回 null)
【发布时间】:2019-02-21 14:03:12
【问题描述】:

无法从 express 表单中读取数据(返回 null),我在 server.js 中使用了正文解析器

//Parser
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());

这是路由方法

router.post('/', async (req, res) => {
    console.log('customer');
    const { error } = validate(req.body);
    console.log(req.body); 
    if (error) return res.status(400).send(error.details[0].message);

    let customer = new Customer({
        name: req.body.name,
        mobile: req.body.mobile,
        isGold: req.body.isGold
    })
    console.log(customer);
    customer = await customer.save();

    res.send(customer);
});

这是 html 表单,我有 3 个字段(名称、移动设备、isGold):-

 <form action="/api/customer" method="POST">
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="name">Full Name</label>
        <input type="name" class="form-control" id="name" placeholder="name">
      </div>   
    </div>
    <div class="form-row">

      <div class="form-group col-md-6">
        <label for="mobile">Mobile</label>
        <input type="mobile" class="form-control" 
        id="mobile" placeholder="Enter your Mobile">
      </div>
    </div>
 
    <div class="form-group">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" id="isGold">
        <label class="form-check-label" for="gridCheck">
          Is Gold
        </label>
      </div>
    </div>
     <button type="submit" class="btn btn-primary">Save</button>
  </form>

【问题讨论】:

  • 您不需要 body-parser,这是 Express 较新版本中的库。替换为express.json()express.urlencoded({ });
  • 好的,但是在使用正文解析器之前我得到了 null。
  • 您还可以通过删除extended: true 标志来进行实验。如果这不起作用,我感觉代码还有更多内容
  • 我看到你没有绑定数据值到http body,你可以试试吗? stackoverflow.com/a/21284362/5589964

标签: node.js express


【解决方案1】:

您需要在输入字段中添加 name 属性

<div class="form-group col-md-6">
        <label for="mobile">Mobile</label>
        <input type="mobile" class="form-control" 
        id="mobile" name="mobile" placeholder="Enter your Mobile">
      </div>
</div>

通常GET/POST请求以key:value对的形式发送。这里的key是表单的name属性。

示例:http://example.com/page?parameter=value&also=another

这里的“参数”(&“也”)是一个表单输入字段名称。

【讨论】:

  • 当我选中复选框时,他们给出了这条消息'"isGold" 必须是布尔值',我如何将其设置为布尔值?
  • 最好在复选框中添加一个值字段。在服务器端,您会在 req.body.name-of-checkbox-field 上获得一组值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多