【问题标题】:How to use Post method in Angular to get如何在 Angular 中使用 Post 方法获取
【发布时间】:2018-02-22 05:22:57
【问题描述】:

无法使用 mysql AnglerJS 和 Spring 控制器将数据插入数据库。给出 400 错误。试图谷歌它,但没有得到代码。所以我在哪里犯了错误

Controller.java

@RequestMapping(value="/insert",method=RequestMethod.POST)
public Emp insret(@RequestParam(value="user")String 
user,@RequestParam(value="pass1")String pass)
{
     Emp em=new Emp();
     em.setUser(user);
     em.setPass(pass);
     System.out.println(user+""+pass);
     return er.save(em);

}

post 方法的 Angular 文件

script1.js

   var app = angular.module("myApp", [])
        .controller("myCtrl", function ($scope, $http, $log) {

            $scope.abc = function () {
                $log.info($scope.user)
                $log.info($scope.pass1)// you will have your updated value here
                $http({
                method:'POST',
                url:     '/insert',

                data : {
                    'user' : $scope.user,
                    'pass':$scope.pass1
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            })
            .then(function (response) {
                 $scope.repos = response.data;
                 $log.info(response);
             });
        }
});

在 HTML 文件中嵌入角用于 post 方法。

index.html

   <!DOCTYPE html>
      <html>
        <head>
          <script 
     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js">
    </script>
          <script type="text/javascript" src="script1.js"></script>
        </head>
          <body ng-app="myApp" >
            <div ng-controller="myCtrl">
               <form ng-submit="abc()">
                  <input type="text"  ng-model="user" />
                  <input type="text"  ng-model="pass1" />
                  <button type="submit">Test</button>
               </form>
            </div>
          </body>
      </html>

如果我将其插入数据与此 URL localhost:8080/insert 一起使用。但如果我使用 角度其 400 错误`

`@RequestMapping(value="/insert")
  public Emp insret() 
 {
  Emp em=new Emp(); 
  em.setUser("etc"); 
  em.setPass("1234"); return er.save(em); 
 } 

【问题讨论】:

  • 只是想知道,您是否尝试过 'application/json' 作为内容类型?
  • POST localhost:8080/insert 400 () 当我使用 'application/json' 时出现这个错误
  • 没有网络上下文路径?
  • 如果服务器接受Content-Typeapplication/x-www-form-urlencoded,您是否尝试过序列化data?比如使用data: $.param({user: $scope.user, pass: $scope.pass1})
  • @shaochuancs 我试过它不插入

标签: angularjs http spring-mvc


【解决方案1】:

正式回答:

@PostMapping(value="/insert",produces="application/json")
public Emp insret(@RequestBody Emp em){
 //do ....
 return er.save(em);
}

当您从 Angular 或其他客户端发布数据时,这些数据位于请求正文中,这就是 Spring 家伙引入此注解的原因。

@RequestParam 用于检索请求参数值,在您的情况下,它会像:/insert?user=value1&amp;pass1=value2 这不是您想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2017-02-24
    • 2019-07-19
    • 2015-09-24
    相关资源
    最近更新 更多