The following Node.js code:
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);
}
});
}();
sends the following http GET request query that is received by like this:
{"packages"=>{"0"=>"example1", "1"=>"example2", "2"=>"example3"}, "os"=>"linux", "pack_type"=>"npm"}
How can I optimize this request to be received like this:
{"packages"=>["example1", "example2", "example3"], "os"=>"linux", "pack_type"=>"npm"}
Note. The REST API is built in Ruby on Rails
If the array need to be received as it is, you can set
useQuerystring
astrue
:UPDATE:
list
key in the following code example has been changed to'list[]'
, so that OP's ruby backend can successfully parse the array.Here is example code:
In this way, when the HTTP
GET
request is sent, the query parameters would be:and the
list
field would be parsed as['XXX', 'YYY', 'ZZZ']
Without
useQuerystring
(default value asfalse
), the query parameters would be:I finally found a fix. I used 'qs' to stringify 'options' with {arrayFormat : 'brackets'} and then concatinated to url ended with '?' as follows:
Note: I tried to avoid concatenation to url, but all responses had code 400