1

Let me start by saying I am a total newbie/hack. The answer is probably very easy... I apologize in advance.

I am sending an object via jquery $.ajax (POST) to a Node.js server running express. The object looks something like this on my server before I make the Ajax call:

var data = {
  "to" : "[email protected]",
  "attachment" : [{"file": "somefile.jpg"}, {"file": "someOtherFile.jpg"}]
}

This is the call to my server:

$.ajax({
    type: "POST",
    url: "http://myHostHere.com",
    data: data,
    success: function(data){
      console.log("Success... Returned Data: " + data);
    }
});

On my Node server here is the route that accepts the request:

app.post('/send/', urlEncodeParser, function(req, res){
        console.log("Req Body: " + JSON.stringify(req.body));
      });

The urlEncodeParser middleware refers to this code:

let urlEncodeParser = bodyParser.urlencoded({ extended:false });     

My receiving Node server receives the object and I can easily get the value of "to" via req.body.to no problem... For some reason I can't figure out how to access the 'file' values though. When I console.log the req.body on my Node server I see now that my object looks different.

Specifically I call console.log(JSON.stringify(req.body))

The output to the console looks like this:

"to" : "[email protected]",
"attachment[0][file]" : "somefile.jpg",
"attachment[1][file]" : "someOtherFile.jpg"

I cannot figure out how to access the value of attachment[0][file] in my code. I have tried req.body.attachment[0].file and req.body.attachment[0][file] and req.body.attachment[0]['file'] each time I get an error TypeError: Cannot read property '0' of undefined

Also I try to just console.log("attachment: " + req.body.attachment) and I get attachment: undefined.

Any help is much appreciated!

2
  • Looks like the middleware didn't parse it, so it's actually req.body["attachment[1][file]"] to access it Commented Mar 2, 2016 at 20:19
  • Thanks @adeneo that works... now to figure out why this is happening. Commented Mar 2, 2016 at 20:22

1 Answer 1

1

You can access the value using the bracket notation:

req.body['attachment[0][file]']

More importantly though is that you find out why your request payload looks like that... Unfortunately you did not provide any information how you send the request...

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

2 Comments

I updated my original post with a little more information... Im thinking this has something to do with the middleware?
@Koreys - look here

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.