[英]How can I deserialize arrays/objects posted to my NodeJS/Express web app?
我正在NodeJS / ExpressJS中编写应用程序。
我有一个这样的表格:
<form method="post" action="/sendinfo">
<label>Name</label>
<input type="text" name="name" />
<label>Address</label>
<input type="text" name="address[number]" />
<input type="text" name="address[street]" />
<input type="text" name="address[suburb]" />
<input type="text" name="address[postcode]" />
<label>Phones</label>
<input type="text" name="phones[0]" />
<input type="text" name="phones[1]" />
</form>
这是我的路线:
app.post('/sendinfo', function (req, res) {
// ...code to save the contents of req.body to the database...
res.render('done');
});
提交表单后,我的req.body
看起来像这样:
{
"name": "Jonathan",
"address[number]": "1",
"address[street]": "Test St",
"address[suburb]": "TestSuburb",
"address[postcode]": "1234",
"phones[0]": "12345678",
"phones[1]": "87654321"
}
但我希望它看起来像这样,嵌套在属性或数组中的值:
{
"name": "Jonathan",
"address": {
"number": "1",
"street": "Test St",
"suburb": "TestSuburb",
"postcode": "1234",
},
"phones": [
"12345678",
"87654321"
]
}
我怎样才能做到这一点?
或者使用urlencoded
中间件(将它放在任何路由之前):
app.use(express.urlencoded());
...
app.post('/sendinfo', function(req, res) {
// req.body will now contain the object you described
...
});
2017年7月16日更新
urlencoded
已从最新版本的express
节点模块中删除,因此请立即使用此功能
const bodyParser = require("body-parser");
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
弄清楚如何。
只需安装querystring包:
`npm install qs --save`
然后像这样称呼它:
app.post('/sendinfo', function (req, res) {
var qs = require('qs');
var deserializedBody = qs.parse(qs.stringify(req.body));
// ...code to save the contents of deserializedBody to the database...
res.render('done');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.