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?

3
  • 2
    IMHO I would never send an array over the HTTP Get params..... Just easier to post them Commented Feb 8, 2016 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. Commented Feb 8, 2016 at 15:32
  • Look into using the alternate param serializer -- AngularJS $httpParamSerializerJQLike Service API Reference. It is more versatile than $httpParamSerializer. Commented Feb 9, 2016 at 2:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.