1

Is there a way I can ajax post an array of objects and have it parsed on a node.js server? 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!

1
  • Which body-parsing middleware are you using? Commented Mar 5, 2016 at 0:21

2 Answers 2

1

This is happening because you aren't sending an object inside of your ajax post, you're sending an array. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you should remove one of the context variables. 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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.