美文网首页我爱编程
Angular http请求后台接受不到参数问题 和跨域问题

Angular http请求后台接受不到参数问题 和跨域问题

作者: Jamesholy | 来源:发表于2017-03-21 17:43 被阅读2373次

    后台接受不到参数问题

    在学习使用angular的$http.post()提交数据时,后台接收不到参数值,于是查阅了相关资料,寻找解决办法。

    前期使用jQuery ajax请求:


    Paste_Image.png

    后台为java,可以取参数。

    Paste_Image.png

    后期使用angularJS 的http进行请求后,

    Paste_Image.png

    后台取出的参数为null。

    查阅资料后发现在angular中,$http的contentType默认值是
    application/json;charset=UTF-8
    这样在后台,SpringMVC通过@RequestParam注解或者request.getParameter()方法是获取不到参数的。

    angularJS请求后参数在request payload里,后端会认为参数非法无法获取

    加如下代码

    Paste_Image.png

    改动后参数在Form Data内,后台测试可以取参数:


    改动后请求

    引入jQuery的话 也可写成

        $http({
                    method:'post',
                    url:'http://192.168.0.116:8080/HighSpeed/speedController/getCode',
                    data:$.param({province: '四川'}),  
                     headers: { 'Content-Type': 'application/x-www-form-urlencoded' }   
                     
                })
    

    源代码

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    
    <script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    </head>
    <body>
    
    <div ng-app="myApp" ng-controller="siteCtrl"> 
    
    <ul>
      <li ng-repeat="x in names">
        {{ x}}
      </li>
    </ul>
    
    </div>
    
    <script>
    var app = angular.module('myApp', []);
    app.controller('siteCtrl', function($scope, $http) {
        
        $http({
                    method:'post',
                    url:'http://192.168.0.109:8080/HighSpeed/speedController/getCode',
                    data:{province: '四川'},
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },    
                    transformRequest: function(obj) {    
                        var str = [];    
                        for (var p in obj) {    
                            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    
                        }    
                        return str.join("&");    
                    }  
                })
      .success(function (response) {$scope.names = response.list;
      });
    });
    </script> 
    
    </body>
    </html>
    

    跨域问题###

    服务器设置:

            /** 设置响应头允许ajax跨域访问 **/
            
            response.setHeader("Access-Control-Allow-Origin", "*");
            /* 星号表示所有的异域请求都可以接受, */
            response.setHeader("Access-Control-Allow-Methods", "POST");
            response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
    

    相关文章

      网友评论

        本文标题:Angular http请求后台接受不到参数问题 和跨域问题

        本文链接:https://www.haomeiwen.com/subject/clpgnttx.html