Reputation: 117
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!
Upvotes: 1
Views: 1459
Reputation: 46351
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...
Upvotes: 1