Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST array data to Express gets parsed out as JSON

My app is Node.js using 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 in my server code:

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

I want to get the array of notes to insert into my DB as an Array. What am I missing?


As I can't add an answer myself for 8 hours (wtf?) BUT it does not really answer why Express.bodyParser does not parse JSON correctly

Ok I can get it to work by using:

JSON.stringify ( data )

on the client then server side using

JSON.parse( req.rawBody )

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

like image 531
JMWhittaker Avatar asked May 08 '11 13:05

JMWhittaker


People also ask

Does Express automatically parse JSON?

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

Can JSON parse an array?

Use the JSON. parse() method to pase a JSON array, e.g. JSON. parse(arr) . The method parses a JSON string and returns its JavaScript value or object equivalent.

Can you send an array as JSON?

JS Array to JSON using JSON.stringify() method converts a JavaScript object, array, or value to a JSON string. If you so choose, you can then send that JSON string to a backend server using the Fetch API or another communication library.

Which method will you use in your Express application to get JSON data from the client side?

body object allows you to access data in a string or JSON object from the client side.


2 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 jQuery mucks around with your data before sending it. If you set the right MIME type, than it leaves you free.

like image 180
Rajat Avatar answered Sep 30 '22 04:09

Rajat


Can you post your client side jQuery code, please? By default jQuery will send data as urlencoded, not JSON. See this question's answer for the way to ensure jQuery sends real JSON data.

FYI the express/connect bodyParser middleware simply uses JSON.parse to parse JSON (and qs.parse to parse urlencoded data). I don't think there are any glaring bugs in those code. Thus I think you should double-check the data you are sending from the browser.

like image 34
Peter Lyons Avatar answered Sep 30 '22 05:09

Peter Lyons