Nodejs – Express – 嵌套的Post数据不能正确parsing

我想发表与嵌套的post元素

在HTML中查看

<form method="post" action=""> <input type="text" placeholder="Enter Tag here" class="gui-input" name="reply_message"> <input type="text" placeholder="Enter Label for Decision" class="gui-input" name="decision[0][label]" value="Interested"> <input type="text" placeholder="Enter decision keywords here" class="gui-input" data-role="tagsinput" name="decision[0][keyword]" value="Interested, call me"> <input type="text" placeholder="Enter Label for Decision" class="gui-input" name="decision[1][label]" value="Not Interested"> <input type="text" placeholder="Enter decision keywords here" class="gui-input" data-role="tagsinput" name="decision[1][keyword]" value="not interested, not"> <input type="text" placeholder="Enter Label for Decision" class="gui-input" name="decision[2][label]" value="Call Later" > <input type="text" placeholder="Enter decision keywords here" class="gui-input" data-role="tagsinput" name="decision[2][keyword]" value="Interested, call me, later"> <button class="button btn-primary" type="submit">Submit </button> 

路由器文件

 router.post('/mapping', isLoggedIn, function (req, res, next) { var posted_data= req.body; console.log(req.body); res.send(posted_data); }); 

我得到像这样的发布数据结构

 { "reply_message": "This is test", "decision[0][label]": "Interested", "decision[0][keyword]": "Interested, call me", "decision[1][label]": "Not Interested", "decision[1][keyword]": "not interested, not", "decision[2][label]": "Call Later", "decision[2][keyword]": "Interested, call me, later" } 

但实际发布的数据结构应该是

 { "reply_message": "This is test", "decision": [{ "label": "Interested", "keyword": "Interested, call me" }, { "label": "Not Interested", "keyword": "not interested, not" }, { "label": "Call Later", "keyword": "Interested, call me, later" }] } 

那么我怎样才能做到这一点,是否有任何节点模块,我必须使用这样的张贴forms的数据?

       

网上收集的解决方案 "Nodejs – Express – 嵌套的Post数据不能正确parsing"

那么, name="decision[0][label]"工作正常。 表单数据作为键值对提交,input名称成为关键字。

如果表单是使用HTTP GET提交的,则会在req.query获得所需的对象。 但是对于HTTP POST,它本身就是req.body

在这里, qs模块可以帮助你在服务器端:

 const qs = require('qs'); const input = { "reply_message": "This is test", "decision[0][label]": "Interested", "decision[0][keyword]": "Interested, call me", "decision[1][label]": "Not Interested", "decision[1][keyword]": "not interested, not", "decision[2][label]": "Call Later", "decision[2][keyword]": "Interested, call me, later" }; const output = qs.parse(qs.stringify(input)); console.log(output); // console: { reply_message: 'This is test', decision: [ { label: 'Interested', keyword: 'Interested, call me' }, { label: 'Not Interested', keyword: 'not interested, not' }, { label: 'Call Later', keyword: 'Interested, call me, later' } ] }