【问题标题】:NodeJS not able to process array of objects received via POSTNodeJS 无法处理通过 POST 接收的对象数组
【发布时间】:2020-04-04 11:51:29
【问题描述】:

我有这个位于 html 文本区域内的对象集合:

{"name":"John", "lname":"Doe","company":"example company","email":"johndoe@example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie@example.com"},
...
...
...

有没有办法将整个集合发送到节点 js 并遍历它以获取对象的值?

我的 AJAX 代码:

  $.ajax({
    type: "POST",
    url: "https://example.com/nodeapp",
    data: '['+document.getElementById("list").value+']',
    success: function(data) {
      console.log(data);
    }
  });

我试图在 req.body 上做一个 foreach,但它似乎不起作用:

var arr = req.body;

arr.foreach(element=>{
console.log(element.email);
})

给出错误:

TypeError: arr.foreach is not a function

【问题讨论】:

标签: javascript node.js ajax express


【解决方案1】:

首先,您必须使用 JSON.parse() 函数来解析正文。 像这样:

var arr = JSON.parse(req.body);

arr.forEach(element=>{
console.log(element.email);
});

javascript 的 foreach 也定义为 arr.forEach(...) 而不是 arr.foreach(...) 。

【讨论】:

    【解决方案2】:

    我发现了我的问题!万一有人被同样的事情困住了,整个事情就是一个字符串:

    '[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe@example.com"},
    {"name":"Katie","lname":"Jake","company":"example company","email":"katie@example.com"},
    ...
    ...]'
    
    

    这被认为是 JSON 中的一个属性,在服务器接收到它时它没有价值。差不多是这样的:

    {
    "<<the array in string format>>" : ""
    }
    

    我解决这个问题的方法是,我将对象分别推送到一个新数组中,然后使用 JSON 内容类型将其发送到服务器。 (这是一个实际的对象数组)

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多