简体   繁体   English

如何将AJAX对象数组发布到node.js服务器?

[英]How can I AJAX POST an array of objects to a node.js server?

Is there a way I can ajax post an array of objects and have it parsed on a node.js server? 有没有一种方法可以使ajax发布对象数组并将其解析到node.js服务器上? Here is my client side code: 这是我的客户端代码:

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);
    }
});

My server side code: 我的服务器端代码:

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

Right now, when I print the request body it returns {} . 现在,当我打印请求正文时,它返回{}

Can someone help me access the array of objects properly on the server side? 有人可以帮助我在服务器端正确访问对象数组吗?

Thanks in advance! 提前致谢!

This is happening because you aren't sending an object inside of your ajax post, you're sending an array. 发生这种情况是因为您没有在ajax帖子中发送对象,而是在发送数组。 Try wrapping the array in {} to signify that it's indeed an object, then reference that object property in your server code. 尝试将数组包装在{}以表示它确实是一个对象,然后在服务器代码中引用该对象属性。

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);
    }
});

Then in your server-side script, you can reference the context property of the body object. 然后,在服务器端脚本中,您可以引用主体对象的context属性。

First of all, you should remove one of the context variables. 首先,您应该删除一个context变量。 There's no need for the second one when you have declared it already at the top. 当您已经在顶部声明它时,就不需要第二个了。

Second, it seems like you're posting to the wrong url, should it be /api/addcompany or /api/addcontact ? 其次,似乎您发布的网址错误,应该是/api/addcompany还是/api/addcontact

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM