我正在玩express并试图理解表单提交的基本工作,我无法获取req.body上的数据(给出空对象)。这是我正在使用的html和js文件。
HTML文件
<form class="form-horizontal" id="form" action="/action" method="post" role="form">
<h2>Registration Form</h2>
<div class="form-group">
<label for="firstName" class="col-sm-3 control-label">Full Name</label>
<div class="col-sm-9">
<input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="">
<span class="help-block">Last Name, First Name, eg.: Smith, Harry</span>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label">Email</label>
<div class="col-sm-9">
<input type="email" id="email" placeholder="Email" class="form-control">
</div>
</div>
</form>
和
Javascript文件
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var MongoClient = require('mongodb').MongoClient;
var myCollection;
app.post('/action', function (req, res) {
console.log("----------------------",req.body);
res.send("done");
});
app.get('/', function (req, res) {
res.sendFile(__dirname+"/signup.html");
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test',
function(err, db) {
if(err)
throw err;
else{
console.log("connected to the mongoDB !");
myCollection = db.collection('test_collection');
}
});
});
答案 0 :(得分:1)
表单输入需要name
才能使bodyparser构建req.body
将name
添加到名字和电子邮件输入字段。
<input type="email" id="email" placeholder="Email" class="form-control" name="email">
<input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="" name="firstName">
答案 1 :(得分:0)
我有类似的问题,但没有键(不是json),它是xml的身体
解决方案如下:https://stackoverflow.com/a/45709414/984471