Nodejs - Express - 嵌套的Post数据无法正确解析

时间:2016-09-23 06:41:56

标签: node.js express

我想发布带有嵌套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"
    }]
}

那么我如何实现这一目标,是否有任何节点模块我必须使用这样的发布表单数据?

1 个答案:

答案 0 :(得分:1)

好吧,const Label = props => <span>{props.content}</span> const Tab = props => <div>{props.content}</div> const Page = () => <Tab content={<Label content='Foo' />} /> 工作正常。表单数据作为键值对提交,输入名称成为关键。

如果表单是使用HTTP GET提交的,那么您将在name="decision[0][label]"中获得所需的对象。但是对于HTTP POST,它按原样进入req.query

在这里,qs module可以帮助您在服务器端:

req.body