以下 Node.js 代码:
var request = require('request');
var getLibs = function() {
var options = { packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' }
request({url:'http://localhost:3000/package', qs:options},
function (error , response, body) {
if (! error && response.statusCode == 200) {
console.log(body);
} else if (error) {
console.log(error);
} else{
console.log(response.statusCode);
}
});
}();
发送以下 http GET 请求查询,该查询由如下方式接收:
{"packages"=>{"0"=>"example1", "1"=>"example2", "2"=>"example3"}, "os"=>"linux", "pack_type"=>"npm"}
如何优化此请求以像这样接收:
{"packages"=>["example1", "example2", "example3"], "os"=>"linux", "pack_type"=>"npm"}
注意。REST API 是用 Ruby on Rails 构建的
如果需要按原样接收数组,则可以useQuerystring
设置为true
:
更新:以下代码示例中list
键已更改为'list[]'
,以便 OP 的 ruby 后端可以成功解析数组。
下面是示例代码:
const request = require('request');
let data = {
'name': 'John',
'list[]': ['XXX', 'YYY', 'ZZZ']
};
request({
url: 'https://requestb.in/1fg1v0i1',
qs: data,
useQuerystring: true
}, function(err, res, body) {
// ...
});
这样,当发送 HTTPGET
请求时,查询参数将为:
?name=John&list[]=XXX&list[]=YYY&list[]=ZZZ
并且list
字段将被解析为['XXX', 'YYY', 'ZZZ']
如果没有useQuerystring
(默认值为false
),查询参数将为:
?name=John&list[][0]=XXX&list[][1]=YYY&list[][2]=ZZZ
我终于找到了解决方法。我使用"qs"将"选项"与{arrayFormat:"括号"}字符串化,然后连接到以"?"结尾的url,如下所示:
var request = require('request');
var qs1 = require('qs');
var getLibs = function() {
var options = qs1.stringify({
packages: ['example1', 'example2', 'example3'],
os: 'linux',
pack_type: 'npm'
},{
arrayFormat : 'brackets'
});
request({url:'http://localhost:3000/package?' + options},
function (error , response, body) {
if (! error && response.statusCode == 200) {
console.log(body);
} else if (error) {
console.log(error);
} else{
console.log(response.statusCode);
}
});
}();
注意:我试图避免连接到url,但所有响应都有代码400
这个问题可以使用请求库本身来解决。 请求内部使用 qs.stringify。您可以传递 q 选项来请求它将用于解析数组参数。
您不需要附加到 url,这会让读者质疑为什么要这样做。
参考: https://github.com/request/request#requestoptions-callback
const options = { method: 'GET', uri: 'http://localhost:3000/package', qs: { packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' }, qsStringifyOptions: { arrayFormat: 'repeat' // You could use one of indices|brackets|repeat }, json: true };