POST array data for Express goes beyond JSON

My Node.js application uses Express.

Sending this test data from my client using jQuery POST:

{ title: 'hello', notes: [ {title: 'note 1'}, {title: 'note 2'} ] 

}

And this is the result of my server code:

 { title: 'hello', notes: { '0': { title: 'note 1' }, '1': { title: 'note 2' } } } 

I want an array of notes to be inserted into my database as an array. What am I missing?


How can I not add the answer myself for 8 hours (wtf?), But it doesnโ€™t actually answer why Express.bodyParser does not parse JSON correctly.

Ok, I can get it to work using:

 JSON.stringify ( data ) 

client side then server side using

 JSON.parse( req.rawBody ) 

This is wrong, and why does Express.bodyParser not correctly parse JSON ?!

+6
source share
4 answers

On your client:

 $.ajax({ type: 'POST', data: JSON.stringify(data), contentType: 'application/json', url: '/endpoint' }); 

On your server:

 console.log('POST: ',req.body); 

The problem is that jQuery disconnects your data before submitting. If you install the correct MIME type, it will set you free.

+16
source

Can you host jQuery client-side code please? By default, jQuery will send the data as urlencoded, not JSON. See this question to ensure jQuery sends real JSON data.

FYI express / connect bodyParser middleware just uses JSON.parse to parse JSON (and qs.parse to parse urlencoded data). I donโ€™t think there are any egregious errors in this code. So, I think you should double check the data that you send from the browser.

+2
source

I came across this old question when I was looking for some other nodejs stuff.

It is a common misconception that jQuery.ajax() functions send data using JSON. The data is sent by jQuery as POST data, not a JSON string. This way all data types (including numbers in your array) are sent as strings.

This means that express parses the "array" keys as a string, and since the array cannot have a string key in javascript without being an object, it is passed to the object.

+1
source

All this makes sense then; you can use Express.bodyParser to get such a result, or you can use JSON.parse or even eval('(' + myPostedData + ')') to get the result object without indexes.

With your current setup, all you have to do is:

 for(var j = 0; j < myVariable.notes.length; j++) { var currentNode = myVariable.notes[j]; //currentode.title should be 'note 1' for j = 0, etc } 
-4
source

Source: https://habr.com/ru/post/887555/


All Articles