1

I'm using Angular's $http.get() method to query my API:

var arr = ['foo','bar'];
return $http.get("api/foo", {
  params: { sampleids: arr}
});

This results in a request to /api/foo?sampleids=115&sampleids=116 which works ok. If I reduce the size of the array to a single element, however, it becomes /api/foo?sampleids=115, which express (node.js) fails to interpret as an array.

If Angular sent the query as /api/foo?sampleids[]=115 instead, it should work fine. Is there any way I can tell it to do that?

Community
  • 1
  • 1
adamdport
  • 11,687
  • 14
  • 69
  • 91
  • 2
    IMHO I would never send an array over the HTTP Get params..... Just easier to post them – Callum Linington Feb 08 '16 at 15:32
  • Hm, that's very interesting. There's no way I know of, aside from producing a little function to manually create such urls. – dmgig Feb 08 '16 at 15:32
  • Look into using the alternate param serializer -- [AngularJS $httpParamSerializerJQLike Service API Reference](https://docs.angularjs.org/api/ng/service/$httpParamSerializerJQLike). It is more versatile than `$httpParamSerializer`. – georgeawg Feb 09 '16 at 02:09

2 Answers2

1

You can use the paramSerializer property in your request config to customize how the parameters object gets converted to a string.

return $http.get("api/foo", {
  params: { myArray: arr},
  paramSerializer: function (params) {
      // Return a string...
  }
});

You can look at the default implementation here, if you're not sure how to go about serializing the object: https://github.com/angular/angular.js/blob/master/src/ng/http.js#L27.

Additionally, if you provide a string rather than a function, it will look for a service with that name - this could be helpful if you want to reuse it. There's a $httpParamSerializerJQLike service provided by default, which serializes them in the same format as jQuery's param() function.

Joe Clay
  • 33,401
  • 4
  • 85
  • 85
0

There seems to be some uncertainty how to best implement arrays as parameters.
You could try using JSON.stringify:

var arr = ['foo','bar'];
$http(
  method: 'GET',
  url: 'api/foo',
  params: {
    arr: JSON.stringify(arr) 
})

Or simply:

var arr = ['foo','bar'];
$http(
  method: 'GET',
  url: 'api/foo',
  params: {
    "arr[]": arr
})

You might find this SO article useful

Community
  • 1
  • 1
sjokkogutten
  • 2,005
  • 2
  • 21
  • 24
  • I linked to that very SO article in my question :) And your simplification becomes `?arr%5B%5D=226&arr%5B%5D=227` (though express doesn't seem to mind) – adamdport Feb 08 '16 at 18:30