2

I'm new to the nodeJS Express framework. I'm consuming a POST request that I sent using the following:

router.post('/', function(req, res) {
    var data = Object.getOwnPropertyNames(req.body)[0];
});

I've sent this data from the client via:

$.ajax({
    url: "write_to_region",
    type: "POST",
    data: JSON.stringify(grid)
});

where "grid" is a 2d array of values. My express body parser is configured as follows:

app.use(bodyParser.urlencoded({limit: '50mb', extended: false }));

What is a better or more idiomatic way of doing this? Note that the array is somewhat large (10kb) and contains only integers. Ideally, I would be minimizing the amount of data sent in the request. Thanks!!

Jon
  • 23
  • 5

1 Answers1

1

The problem is that you're not setting the appropriate Content-Type. Jquery's default Content-Type for POSTing data is application/x-www-form-urlencoded. So the body parser starts reading the request data, looking for an = to know when the "key" ends and the "value" starts. It never finds an = so it keeps appending to the key name.

To fix this you need to add these options in your $ajax() config:

contentType: "application/json; charset=utf-8",
dataType: "json",

and add the bodyParser.json() middleware:

app.use(bodyParser.json());
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Thank you, that worked. I had originally tried `contentType: "application/json"` but ran into what I now realize is [this](http://stackoverflow.com/questions/12693947/jquery-ajax-how-to-send-json-instead-of-querystring). – Jon Oct 31 '14 at 00:40