0

In javascript:

var post = {};
post.arr = ["hi", "hello"];
$.post("http://localhost:8000/test", post);

and in node:

        var body = "";
    request.on('data', function (data) {
        body += data
    });
    request.on('end', function (data) {
        var post = qs.parse(body);
        console.log(post); // I see { 'arr[]': ['hi', 'hello'] };
        console.log(post.arr); // undefined
    }

Any idea what might have caused this?

3
  • 1
    If that's exactly what you see then you just have a string which isn't a valid object (can't have single quotes or semicolons in JSON). If it is an object and you're printing it incorrectly, then you have an object with a key arr[] so you can access it as post['arr[]']. Commented Apr 15, 2016 at 16:30
  • but why did the key change to "arr[]" instead of arr? Commented Apr 15, 2016 at 16:35
  • 1
    Because when jQuery POSTs an array, it adds [] to indicate it's an array. Many languages and frameworks take advantage of this to automatically parse arrays. Commented Apr 15, 2016 at 16:37

1 Answer 1

1

Based on your comments, it looks like somehow the map key is literally arr[]. Try console.log(post['arr[]']);

jQuery will modify the name of arrays as @MikeC pointed out. More info here: https://stackoverflow.com/a/5888057/1861459

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

4 Comments

I'm guessing qs is the queryString library? See updated answer.
data.arr gives undefined
yep, MikeC is right - it's jQuery changing the name. More info here: stackoverflow.com/a/5888057/1861459
Thanks for the link.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.