gpt4 book ai didi

node.js - Nodejs - Express - 嵌套发布数据无法正确解析

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:37 25 4
gpt4 key购买 nike

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

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

最佳答案

嗯,name="decision[0][label]" 工作正常。表单数据作为键值对提交,输入的名称成为键。

如果使用 HTTP GET 提交表单,您将在 req.query 中获得所需的对象。但是对于 HTTP POST,它按原样存在于 req.body 中。

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

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' } ] }

关于node.js - Nodejs - Express - 嵌套发布数据无法正确解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39654207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com