[英]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.在 node.js 中,我使用这里的代码来提取 POST 数据。
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.我正在使用 Python requests 库发出请求。 When the array
foo
has more than one element the output is as expected.当数组
foo
有多个元素时,输出符合预期。
requests.post(url, data={'foo': ['bar', 'baz']})
gives ['bar', 'baz']
requests.post(url, data={'foo': ['bar', 'baz']})
给出['bar', 'baz']
However if the array has only one element in it the variable foo
becomes a string!然而,如果数组中只有一个元素,变量
foo
就会变成一个字符串!
requests.post(url, data={'foo': ['bar']})
gives bar
and not ['bar']
. requests.post(url, data={'foo': ['bar']})
给出bar
而不是['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.然后你用 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:这给您留下了三个选择:
obj[k] = [v];
obj[k] = [v];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.