Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am passing a POST that includes an array of "wines". The object on the send looks line. However when I log the request on the server side, the array is a collection of keys and values. What am I missing:

**** MY TEST REQUESTING CODE ****

request.post("http://localhost:3000/todos", {form: params}, function(err, response){
    console.log(response.body);
})

**** THE OPTION AS IT IS BEING SENT ****

var params = {
    name: 'Test Do',
    summary: 'This is the summary',
    wines: ['56ad66897070ffc5387352dc', '56dg66898180ffd6487353ef']
}

**** MY SERVER SIDE CODE --- SHORTEN FOR BREVITY ***

exports.todoPost = function(req, res){
console.log(req.body);
var todo = new ToDo(req.body);
    todo.save(function(err, todoX){
        if(err){return res.send.err;}
        console.log(req.body.store_config)
        if(todo.wines){

**** THE OUTPUT OF 'console.log(req.body) ****

{ name: 'Test Do',
  summary: 'This is the summary',
  'wines[0]': '56ad66897070ffc5387352dc',
  'wines[1]': '56dg66898180ffd6487353ef' }

Can I not send an array in a POST? Everything I see online and everything I've tried isn't working. It says I'm passing stuff correctly.

share|improve this question
up vote 0 down vote accepted

Technically you did send an array using POST. They're just handled differently. One thing you could do instead is send the object as a JSON string.

request.post("...", { form: JSON.stringify(params) }, function( ...

Then on the server-side, just undo the stringifying by using JSON.parse.

var params = JSON.parse(req.body);
share|improve this answer
    
Is there a way to handle that array as it is received currently? When I console log (todos.wines) or (todos.wines[0]) both come back as null. – KJ Carlson 18 hours ago
1  
@KJCarlson There are. If you're using Express you can install the body-parser module and that should automatically handle converting it to an array. Otherwise, you'll need to either filter out the key names or do the conversion yourself. (Note: try todos['wines[0]'] and you'll get what you want but it won't be in an array.) – Mike C 18 hours ago
    
Thanks, @Mike-C. I realized I was trying to call it after I had already cast it to the model instead of pulling out the variable from the req.body['wines[0]'] – KJ Carlson 17 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.