589

I have a function which does a http POST request. The code is specified below. This works fine.

 $http({
   url: user.update_path, 
   method: "POST",
   data: {user_id: user.id, draft: true}
 });

I have another function for http GET and I want to send data to that request. But I don't have that option in get.

 $http({
   url: user.details_path, 
   method: "GET",
   data: {user_id: user.id}
 });

The syntax for http.get is

get(url, config)

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Chubby Boy
  • 30,942
  • 19
  • 47
  • 47

7 Answers7

958

An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.

angular.http provides an option for it called params.

$http({
    url: user.details_path, 
    method: "GET",
    params: {user_id: user.id}
 });

See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)

Ricky Dam
  • 1,833
  • 4
  • 23
  • 42
fredrik
  • 17,537
  • 9
  • 51
  • 71
  • 17
    this will return a promise – Connor Leech Mar 11 '14 at 07:12
  • 1
    The code with the promise: $http({method: 'GET', url: '/someUrl'}). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. }); – Ehud Grand Sep 01 '14 at 07:44
  • 134
    Angular also provides the functionality in the `$http.get(url.details_path, {params: {user_id: user.id}})`. – enpenax May 29 '15 at 04:28
  • This aproach doesn't allow to send complex objects – Vildan Nov 12 '15 at 05:21
  • 16
    It would have been nice to keep the object key consistent between HTTP verbs... having data for POST and params for GET is counterintuitive. – Hubert Perron Mar 09 '16 at 14:36
  • I dont understand the Angular documentation here. it says `$http.get()` may include a "config object", but no link is given whatsoever, explaining what in the world a config object is meant to include....... – phil294 Jul 27 '16 at 09:33
  • 8
    @HubertPerron Actually it is not counterintuitive since these are different things: DATA can represent an object/model, even nested, and becomes part of the POST header... PARAMS represent what you can add to the GET url, where each property represents a part of the querystring in the url. It's good that they have different naming because it makes you aware of the fact that you are doing something different. – Jos Nov 09 '16 at 09:15
  • @HubertPerron don't forget, also, that a POST request can have both data AND query parameters as well. – gilad905 Mar 06 '18 at 10:51
  • Works Angular 1.3.2 – sg28 Mar 06 '18 at 23:37
528

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});
Rob
  • 12,659
  • 4
  • 39
  • 56
  • 2
    This works but the params object is being converted into String. How do i retain the original object? – wdphd Mar 02 '15 at 16:23
  • 13
    @wdphd It is inherent to HTTP that it wll be encoded to a query string – Uli Köhler Mar 08 '15 at 19:19
  • 1
    @Uli Köhler: Yup, Missed this. I was thinking along the lines of UI router where you can specify the params data type. Fixed this with a simple parseInt on the backend. – wdphd Mar 09 '15 at 04:25
  • 2
    This is the correct solution if you want to add GET parameters to the given URL and works perfectly fine. – enpenax May 29 '15 at 04:26
  • Some co workers have a concern with the lenght of thr url, is this really an issue? – Juan Dec 24 '15 at 01:09
  • 1
    @Juan, http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers – Rob Dec 24 '15 at 18:25
44

Starting from AngularJS v1.4.8, you can use get(url, config) as follows:

var data = {
 user_id:user.id
};

var config = {
 params: data,
 headers : {'Accept' : 'application/json'}
};

$http.get(user.details_path, config).then(function(response) {
   // process response here..
 }, function(response) {
});
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • 1
    But this data still isn't in a request body. – naXa stands with Ukraine Aug 02 '16 at 08:50
  • 1
    @naXa GET should be url params only by convention, so many frameworks will not allow it to enforce best practice, even if technically it could work and could make sense. – Christophe Roussy May 29 '17 at 08:28
  • 1
    If only the AngularJS documentation could have provided this simple example! – Norbert Norbertson Nov 27 '17 at 15:45
  • @Arpit Aggarwal would you be so kind in having a look at my similar question with golang web server and vue.js? https://stackoverflow.com/questions/61520048/how-to-exchange-data-between-go-web-server-and-vue-js-frontend-http-post-404?noredirect=1#comment108824929_61520048 – user2315094 Apr 30 '20 at 10:47
34

Solution for those who are interested in sending params and headers in GET request

$http.get('https://www.your-website.com/api/users.json', {
        params:  {page: 1, limit: 100, sort: 'name', direction: 'desc'},
        headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
    }
)
.then(function(response) {
    // Request completed successfully
}, function(x) {
    // Request error
});

Complete service example will look like this

var mainApp = angular.module("mainApp", []);

mainApp.service('UserService', function($http, $q){

   this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {

        var dfrd = $q.defer();
        $http.get('https://www.your-website.com/api/users.json', 
            {
                params:{page: page, limit: limit, sort: sort, direction: direction},
                headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
            }
        )
        .then(function(response) {
            if ( response.data.success == true ) { 

            } else {

            }
        }, function(x) {

            dfrd.reject(true);
        });
        return dfrd.promise;
   }

});
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
4

You can even simply add the parameters to the end of the url:

$http.get('path/to/script.php?param=hello').success(function(data) {
    alert(data);
});

Paired with script.php:

<? var_dump($_GET); ?>

Resulting in the following javascript alert:

array(1) {  
    ["param"]=>  
    string(4) "hello"
}
Jeffrey Roosendaal
  • 6,872
  • 8
  • 37
  • 55
  • 2
    does $http do any escaping? – Michael Cole Oct 17 '14 at 18:13
  • 2
    This works too but the issue with this is that when you have multiple parameters it becomes a pain adding them to the end of the url plus if you change a variable name you have to come and change it in the url as well. – user3718908x100 Jul 29 '15 at 16:40
  • I know. It was more a demonstration, showing that *you can even do it the regular way*, I don't necessarily recommend it. (Where 'regular way' means how you've probably done it for years with php) – Jeffrey Roosendaal Jul 30 '15 at 10:49
2

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120
1

For sending get request with parameter i use

  $http.get('urlPartOne\\'+parameter+'\\urlPartTwo')

By this you can use your own url string

Mohib
  • 176
  • 1
  • 5
  • 20