【发布时间】: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