我正在尝试使用 jQuery 向我的 Node 应用程序发送 POST 请求,其中包含数据中的对象数组。当请求正文到达服务器时,数组数据会被散布到各个字段中,使我无法使用数组函数。
数据对象
keyworddata = [
{
field1 : 'foo1',
field2 : 'bar1'
},
{
field1 : 'foo2',
field2 : 'bar2'
}
]
postdata =
{
newtitle : 'New Title',
newtopic : 'New Topic',
keywords : keyworddata
}
jQuery 发布
function postNewData(senddata) {
$.post("/data/add", senddata, function(data,status,xhr){
//wanting to do some stuff here
});
};
postNewData(postdata);
Controller 代码 -/data/add 路由将请求发送到此函数
exports.addNewData = (req, res) => {
console.log(req.body);
//need to iterate over req.body.keywords as an array but can't
}
服务器上的控制台显示 - 关键字数组被拆分为各个字段
{
'newtitle' : 'New Title',
'newtopic' : 'New Topic',
'keywords[0][field1]' : 'foo1'
'keywords[0][field2]' : 'bar1'
'keywords[1][field1]' : 'foo2'
'keywords[1][field2]' : 'bar2'
}
我还尝试使用 stringify
构建数据并发送到 post 请求
keyworddata = [
{
field1 : 'foo1',
field2 : 'bar1'
},
{
field1 : 'foo2',
field2 : 'bar2'
}
]
postdata =
{
newtitle : 'New Title',
newtopic : 'New Topic',
keywords : JSON.stringify(keyworddata)
}
使用stringify
数据像这样到达 Node
{
'newtitle' : 'New Title',
'newtopic' : 'New Topic',
'keywords' : '[{"field1":"foo1","field2":"bar1"},{"field1":"foo2","field2":"bar2"}]'
}
这看起来更接近,但我无法针对字符串运行数组函数,并且找不到解决方法来将其返回到对象数组。
我还尝试使用 $.ajax
调用,但得到与上面相同的结果。
最佳答案
使用 JSON.parse(string)
可以。示例代码是:
const reqContent = {
'newtitle': 'New Title',
'newtopic': 'New Topic',
'keywords': '[{"field1":"foo1","field2":"bar1"},{"field1":"foo2","field2":"bar2"}]'
};
const keywords = JSON.parse(reqContent.keywords);
console.log(keywords);
关于jQuery POST 将对象数组发送到 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63161828/