jQuery POST 将对象数组发送到 Node

标签 jquery node.js arrays post

我正在尝试使用 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/

相关文章:

javascript - 在克隆的图像元素上绑定(bind) onclick 事件

mysql - 具有复合主键和特定 VARCHAR 长度的 NodeJS MySQL ORM

javascript - 将数组中的两个对象与变量进行比较以显示第三个对象

node.js - 在 MongoDB 和 Node.js 中获取字段的所有值的最有效方法

node.js - 用于 bower 组件的 Express.js 路由

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

ios - 设置 TextView 以查看数组中的所有元素

javascript - css 中的响应表

javascript - 更新后焦点丢失

javascript - 如何正确堆叠砌体布局和延迟加载图像?