javascript angularjs $http.post 带参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33355497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:24:30  来源:igfitidea点击:

angularjs $http.post with parameters

javascriptangularjs

提问by gsiradze

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

我是 angular 新手,如果我的问题有点低,请不要生我的气。

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

如果用户通过身份验证,我有返回 sessionId 和登录成功消息的 Web 服务。例如网址是:

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

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).

我的范围内有 user.username 和 user.password(使用文本框)。

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

如何在 url 中传递这些参数以及如何解析该响应?

回答by JasperZelf

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:

在您的代码中,您在 POST 请求的 URL 中传递用户名和密码。如果那是您真正想要的(将它们作为 POST 数据传递更常见),那么您可以使用以下命令:

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:

如果要将数据作为 POST 数据传递,可以将其作为$http.post()调用中的第二个参数传递:

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");
        }
    });
};

回答by Hitmands

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

我从未见过任何人通过查询字符串传递登录数据,如果您使用的是简单的 http 协议……您应该考虑使用基本访问身份验证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>