您正在正确使用 Express 正文解析器中间件括号表示法。但是,作为可以做什么的一个例子......
使用此视图:
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[0][email]" type="email" value="email1@example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[1][email]" type="email" value="email2@example.com"> <br>
<button type="submit">Submit v1</button>
</form>
<br>
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[email][0]" type="email" value="email1@example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[email][1]" type="email" value="email2@example.com"> <br>
<button type="submit">Submit v2a</button>
</form>
<br>
<form method="post">
<label for="person_email_1">Email address 1</label>
<input id="person_email_1" name="person[email]" type="email" value="email1@example.com"> <br>
<label for="person_email_2">Email address 2</label>
<input id="person_email_2" name="person[email]" type="email" value="email2@example.com"> <br>
<button type="submit">Submit v2b</button>
</form>
<br>
<form method="post">
<label for="person_email_1_address">Email address 1</label>
<input id="person_email_1_address" name="person[emailAddresses][0][address]" type="email" value="email1@example.com">
<input id="person_email_1_description" name="person[emailAddresses][0][description]" type="text" value="lorem ipsum 1"> <br>
<label for="person_email_2_address">Email address 2</label>
<input id="person_email_2_address" name="person[emailAddresses][1][address]" type="email" value="email2@example.com">
<input id="person_email_2_description" name="person[emailAddresses][1][description]" type="text" value="lorem ipsum 2"> <br>
<button type="submit">Submit v3</button>
</form>
...和这个帖子处理程序:
function postHandler(req, res) {
console.log(JSON.stringify(req.body)); // show in console
res.send(req.body); // show in browser
}
版本 1(您的版本,适用于我,并返回您想要的结果)req.body:
{
"person": [
{"email": "email1@example.com"},
{"email": "email2@example.com"}
]
}
版本 2a 和 2b(字符串数组,带/不带索引号)req.body:
{
"person": {
"email": [
"email1@example.com",
"email2@example.com"
]
}
}
版本 3(对象数组)req.body:
{
"person": {
"emailAddresses": [
{
"address": "email1@example.com",
"description": "lorem ipsum 1"
},
{
"address": "email2@example.com",
"description": "lorem ipsum 2"
}
]
}
}
我个人在 node/Express/jquery/Bootstrap 业务线应用程序上使用了版本 2 和 3,其中个人或企业帐户可以拥有无限的电话号码、电子邮件地址和 URL。body-parser 括号符号让它变得很容易。