angularjs $http.post with parameters

All we need is an easy explanation of the problem, so here it is.

I’m new at angular and if my question is kinda low lvl dont be angry with me.

I have web service which returns sessionId and login success message if user will pass auth. for example url is that:

http://localhost:8181/login?username=USERNAME&password=12345

and here’s my response:

{"sessionId":"0997cec2a8b34c84ba8419ab1204e6aa","loginSucceeded":true}

here’s my login controller:

app.controller('loginCtrl', function($scope, loginService){
    $scope.login=function(user){
        loginService.login(user);
    }
});

and here’s my service:

app.factory('loginService', function($http){
    return{
        login: function(user){
            var $promise=$http.post('http://localhost:8181/login?', user);
            $promise.then(function(msg){
                if(msg.loginSucceeded=="true")
                    console.log("opa")
                else
                    console.log("den");
            });
        }
    }
});

and I have user.username and user.password in my scope (using textboxes).

How can I pass those parameters in url and how can I parse that response?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In your code you’re passing the username and password in the URL of the POST request. If that’s what you really want (it’s more common to pass them as POST data) than you can use this:

login: function(user){
    var url = 'http://localhost:8181/login?username=' + user.name + '&password=' + user.password;
    $http.post(url).then(function(msg){
        if(msg.loginSucceeded==="true"){
            console.log("opa")
        }else{
            console.log("den");
        }
    });    
}

If you want to pass the data as POST data, you can pass that as the second argument in the $http.post() call:

login: function(user){
    var url = 'http://localhost:8181/login';
    var data = {username: user.name, password: user.password};
    $http.post(url, data).then(function(msg){
        if(msg.loginSucceeded==="true"){
            console.log("opa")
        }else{
            console.log("den");
        }
    });
};

Method 2

I never seen anyone passing login data via query string,
if you are in simple http protocol… you should consider using Basic Access Authentication or oAuth

by the way, if you need to do what described above… this could be help you!

angular
  .module('test', [])
  .service('LoginService', function($q, $http) {
    var self = this;
  
    self.login = function(username, password) {
      var configs = { cache: false };
      var payload = {
        "username" : username,
        "password" : password
      };
      
      // The Method Post is generally used with a payload, but if you need to pass it as query string... you have to do:
      configs.params = payload;
      return $http
        .post('/api/login', null /* but normally payload */, configs)
        .then(function(result) { 
          console.log('LoginService.login:success', result); 
          return result.data;
        })
        .catch(function(error) {
          console.log('LoginService.login:error', error);
          return $q.reject(error);
        });
      ;
    };
  })
  .controller('LoginCtrl', function(LoginService, $scope) {
    var vm = $scope
    vm.username = 'hitmands';
    vm.password = 'helloWorld';
    vm.debug = 'CIAO';
  
    vm.onFormSubmit = function(event, form) {
      if(form.$invalid) {
        event.preventDefault();
        return;
      }
      
      vm.debug = null;
      
      return LoginService
      .login(vm.username, vm.password)
      .then(function(data) { vm.debug = data; })
      .catch(function(error) { vm.debug = error; })
    ;
      
    };
  })
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<article ng-app="test">
  <div ng-controller="LoginCtrl">
    <form ng-submit="onFormSubmit($event, loginForm);" name="loginForm">
      <input type="text" placeholder="username" ng-model="username">
      <input type="password" placeholder="Password" ng-model="password">
      <div>
        <button type="submit">Send Login Data</button>
      </div>
      
      <div style="color: blue; padding: 1em .5em;" ng-bind="debug | json">
      </div>
    </form>
  </div>
</article>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply