How to do a $http GET with some data in AngularJS?

后端 未结 4 1688
忘了有多久
忘了有多久 2021-01-04 21:26

I want to make a Get request to my Backend, but I want to verify some user credentials before sending the response object.

Here is my code:

$scope.ge         


        
相关标签:
4条回答
  • 2021-01-04 22:01

    Try

    var req = {
     method: 'GET',
     url: 'http://localhost:1234/things',
     data: { test: 'test' }
    }
    
    $http(req).then(function(){...}, function(){...});
    
    0 讨论(0)
  • 2021-01-04 22:15

    If you want to pass some data on using GET method you can pass a params options on the get method of the $http service. This will be urlencode parameters

    $http.get(url, {
      params: {
        query: 'hello world'
      }
    } 
    

    or

    $http({
       url: url,
       method:'GET',
       params: {
         query:'Hello World'
       }
    })
    

    But, the http standars define the POST method to send data to the server. The GET is just to obtain data from it. On angular the post method:

    $http({
      url: url,
      method:'POST',
      data: {
        query: 'Hello World'
      }
    })
    

    check the official docs from GET and POST

    0 讨论(0)
  • 2021-01-04 22:20

    You're most likely going to need to use a POST method instead of a GET method.

    But to do it with a GET method:

    From AngularJS passing data to $http.get request:

    A 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 params.

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

    And using AngularJS to POST instead:

    $http.post('/someUrl', {msg:'hello word!'}).
      then(function(response) {
        // this callback will be called asynchronously
        // when the response is available
      }, function(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    
    0 讨论(0)
  • 2021-01-04 22:20

    For $http.get requests use the params property of the config object

    $http.get(url, {params:{ foo:'bar'}}).then(func....
    

    See the Arguments table in Usage section of $http docs

    0 讨论(0)
提交回复
热议问题