Perrier February 2016

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);
        });

Answers


stdob-- February 2016

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);
        });

Post Status

Asked in February 2016
Viewed 3,605 times
Voted 6
Answered 1 times

Search




Leave an answer