无法从快速表格中读取数据(返回null)

时间:2019-02-21 14:03:12

标签: node.js 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个字段(name,mobile,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>

1 个答案:

答案 0 :(得分:0)

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

<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是表单的名称属性。

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

“ parameter”(&“ also”)是表单输入字段的名称。