【问题标题】:How can I AJAX POST an array of objects to a node.js server?如何通过 AJAX 将对象数组发布到 node.js 服务器?
【发布时间】:2016-06-18 20:40:33
【问题描述】:

有没有办法可以通过 ajax 发布一组对象并在 node.js 服务器上对其进行解析?这是我的客户端代码:

var context = [];

obj1 = {
      first_name: 'e',
      last_name: 'e',
      contact_email: 'e',
      contact_phone_num: 'e',
      contact_notes: 'e' 
  }


  obj2 = {
      first_name: 'a',
      last_name: 'a',
      contact_email: 'a',
      contact_phone_num: 'a',
      contact_notes: 'a' 
  }


  var context = [];

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: context,
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

我的服务器端代码:

api.post('/api/addcompany', function(req, res) {
    console.log('add company hit');
    console.log(req.body);  //returns {}
    res.sendStatus(200);
});

现在,当我打印请求正文时,它返回 {}

有人可以帮我在服务器端正确访问对象数组吗?

提前致谢!

【问题讨论】:

  • 您使用的是哪个正文解析中间件?

标签: javascript arrays ajax node.js object


【解决方案1】:

发生这种情况是因为您没有在 ajax 帖子中发送对象,而是发送了一个数组。尝试将数组包装在 {} 中以表示它确实是一个对象,然后在您的服务器代码中引用该对象属性。

var context = []; // array

  context.push(obj1);
  context.push(obj2)


  $.ajax({
    type: "POST",
    url: '/api/addcontact',
    data: {context: context}, // requires an object here
    success: function(data, status) {
        alert('company added!');

    },
    error: function(data, status, res) {
        console.log('err: ' + res);
    }
});

然后在你的服务器端脚本中,你可以引用body对象的context属性。

【讨论】:

    【解决方案2】:

    首先,您应该删除context 变量之一。如果您已经在顶部声明了第二个,则不需要第二个。

    第二,好像发错网址了,应该是/api/addcompany还是/api/addcontact

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      相关资源
      最近更新 更多