Perrier
Perrier

Reputation: 2827

express4 bodyparser post array item is udefined

I have an express application that uses bodyParser to get json content from a post request. If I write out the content of the whole body it looks like this:

{
  'device[group]': 'TESTGROUP',
  'device[name]': 'TESTNAME',
  'events[http][address]': 'http://192.168.77.11/api'
}

Immediately after I write out the content of events which gives me undefined. What am I doing wrong?

My code is as follows:

app.post('/settings', function(req, res) {
    console.log(req.body);
    console.log(req.body.events); // undefined

Client side code:

$.ajax({
            url: postURL,
            data: {
                    "device": {
                        "group": $('#devicegroup').val(),
                        "name": $('#devicename').val()
                    },
                    "events": {
                        "http": {
                            "address": $('#httpaddress').val()
                        }
                    }
            },
            type: 'POST',
            dataType: 'json'
        }).success(function(response) {
            console.log(response);
        });

Upvotes: 0

Views: 97

Answers (1)

stdob--
stdob--

Reputation: 29172

You need send data as String, not as PlainObject:

$.ajax({
            url: postURL,
            data: JSON.stringify( {
                    "device": {
                        "group": $('#devicegroup').val(),
                        "name": $('#devicename').val()
                    },
                    "events": {
                        "http": {
                            "address": $('#httpaddress').val()
                        }
                    }
            } ),
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json'
        }).success(function(response) {
            console.log(response);
        });

Upvotes: 1

Related Questions