0

I'm pretty new to javascript and i'm trying to send an object with an other object inside trought post method:

$.post('/posttest', {tableName : 'WSTest', data : {name : "Rachid", age : 42, ville : "Tokyo"}}).done(function(data) {
      console.log("data posted : ", data);
  });

I can retrieve tableName with req.body.tableName but req.body.data give me undefined. When i console.log(req.body) i got:

{ tableName: 'WSTest',
  'data[name]': 'Rachid',
  'data[age]': '42',
  'data[ville]': 'Tokyo' }

As far as i understand it, javascript takes data as a dico ? How can i make data as an object ?

1
  • You're sending it correctly, jQuery converts it to www-urlencoded with the multiple keys and brackets etc, it's the server that doesn't parse it correctly. What bodyParser are you using Commented Nov 17, 2016 at 15:29

1 Answer 1

1

Standard form encoded data is a flat data structure. It is just key/value pairs.

A non-standard extension to the syntax was introduced by PHP which allows you to describe nested data, but your parser doesn't appear to recognise it.

To access the data you will need to mention the square brackets.

req.body["data[name]"]
// etc

Alternatively, find a parser which does recognise the square brackets as having special meaning.

Assuming you are using the (fairly common) "URL-encoded form body parser" feature of the body-parser module, see the docs:

extended

The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

So:

app.use(bodyParser.urlencoded({ extended: true }));

… will probably do the trick.

Sign up to request clarification or add additional context in comments.

2 Comments

Generally, the Express bodyParser should handle this if set to bodyParser.urlencoded({ extended: true })
client side : var str = JSON.stringify(myObjToSend); server side: var myObj = JSON.parse(str);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.