-2

In node.js, I'm using code from here to extract POST data.

that is:

var qs = require('querystring');
function (request, response) {
    if (request.method == 'POST') {
        var body = '';
        request.on('data', function (data) {
            body += data;
            request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            console.log(post.foo);
        });
    }
}

I am making requests using the Python requests library. When the array foo has more than one element the output is as expected.

requests.post(url, data={'foo': ['bar', 'baz']}) gives ['bar', 'baz']

However if the array has only one element in it the variable foo becomes a string!

requests.post(url, data={'foo': ['bar']}) gives bar and not ['bar'].

I would like to not do something like:

if (typeof post.foo === 'string')
    post.foo = [post.foo]

to ensure that the client sends only arrays.

Community
  • 1
  • 1
rohithpr
  • 6,050
  • 8
  • 36
  • 60

1 Answers1

1

The query string format has no concept of "arrays".

The library you are using will just, when given an array of data, insert duplicate keys into the result. This is a standard practise.

So:

requests.post(url, data={'foo': 'one-value-only', 'bar': ['first-value', 'second-value']})

will give you:

foo=one-value-only&bar=first-value&bar=second-value

Then you parse that in JavaScript. You can see the source code from the library you are using. If it gets a second key with a given name, it replaces the value it returns with an array.

Nothing in that code gives you an option to always return an array.

That leaves you with three options:

  1. Perform the test on the results that you say you don't want to perform
  2. Edit the querystring library so that line 71 reads obj[k] = [v];
  3. Use a different library
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335