简体   繁体   中英

How to prevent an array of unit length in POST body from being converted to a string?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM