2

with this code I am trying to send a $http.get request to my rest service:

$http({
    method: 'GET',
    url: '/api/item/all',
    params: {
        query: {
            userid: 7
        },
        fields: 'title'
    }
});

I expected to access this URL:

/api/item/all?query[userid]=7&fields=title

but I am always getting a malformed url...

So, how to proceed?

Or even better: Is it possible to pass the full request url into the url-param of $http?

donnikitos
  • 776
  • 1
  • 9
  • 18
  • You should be fine to write the url with the full query string unless there are variables – Explosion Pills Jul 11 '14 at 23:42
  • 1
    could try `"query[userid]" : 7 , fields: 'title'` – charlietfl Jul 11 '14 at 23:46
  • @ExplosionPills the user id is a variable... should I first create a string with the url and then pass it to $http? – donnikitos Jul 11 '14 at 23:48
  • @charlietfl already tried... doesn't pass the variable at all. – donnikitos Jul 11 '14 at 23:49
  • OK. I didn't realize it was a variable. Can you change back end, that's an ugly looking url especially since `userid` is a variable. Alternatively creating the string in advance is not an issue either – charlietfl Jul 11 '14 at 23:56
  • Exact duplicate of [AngularJS passing data to $http.get request](http://stackoverflow.com/questions/13760070/angularjs-passing-data-to-http-get-request). The solution is to use the `params` option. – Dan Dascalescu Oct 27 '14 at 10:58
  • If you are facing AngularJS specific serialization problem, then httpParamSerializerJQLike is what you need. Take a look at http://stackoverflow.com/questions/33852190/angularjs-get-ajax-call-with-array-parameters – VivekDev Nov 24 '15 at 04:48

1 Answers1

-4

In a GET request, you should pass parameters as part of the query string.

You can use the shortcut get call and pass in the query parameters in the url:

$http.get('api/item/all?userid=" + 7 + "&fields=title");

If you need to access them as scope variables, you can do that too:

$http.get('api/item/all?userid=" + $scope.foo + "&fields=" + $scope.bar);

Also depending on the back end you can send them as a path parameters rather then a query parameter:

$http.get('api/item/all/userid/" + $scope.foo + "/fields/" + $scope.bar);

Hope that helps

arthurzp
  • 109
  • 3
  • 3
    Please don't build query strings by hand! You'll have to escape the values manually. Much better to use the [`params` option of the config object](http://stackoverflow.com/questions/13760070/angularjs-passing-data-to-http-get-request). – Dan Dascalescu Oct 27 '14 at 10:58
  • I have to emphatically agree with Dan Dalcalescu. I'm currently dealing with a lot of issues on our web app because someone prior built up strings by hand. Why choose a fragile methodology as best practice rather than using the framework that you've been provided? – JohnMetta Jun 14 '15 at 20:31