【问题标题】:Solving CORS when posting in angularJs using $HTTP with credentials使用带有凭据的 $HTTP 在 angularJs 中发布时解决 CORS
【发布时间】:2015-09-02 07:03:03
【问题描述】:

点击提交按钮后,emailId 和密码被解析并通过 $http 方法发送。

服务器拒绝接受Api调用,因为服务器和客户端有不同的IP和端口。

服务器响应标头启用了 java CORS 过滤器。

服务器在 STS 上运行并托管在 Apache Tomcat 上,前端托管在 Web Storm 服务器上。

DB 通过 java 控制器中的@requestbody 映射连接。

我已经在客户端包含了所有可能的标头组合,但它没有帮助。

我尝试了内容类型:'application/x-www-form-urlencoded' 以及 text/html 和 application/json。似乎没有任何效果。

服务器弹出的错误是:“XMLHttpRequest 无法加载 http://182.72.xxx.xxx:9090/incite-merchant/connects/login。请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此不允许访问 Origin 'http://192.168.x.xxx:8080'。 "

寻求帮助。

index.html

<div data-ng-app = "inciteapp" data-ng-init = "name= 'cafe'" container = "pizzaContainer">
<div ng-controller="pizzaController" class="email" data-ng-submit = "userInfo()" data-ng-model="name" style="width:24em" autoscroll>

<p style="font-size:18px">Login from your mail.&nbsp; OR &nbsp;&nbsp;<a href="#2" data-ng-click="signuplink()">Sign-up now</a></p>

<form class="form-horizontal form-group" form-submit = "submit()" id="myform" role="form" action="/server" name="loginform" novalidate>

<div>EmailId <span style="color:red">*</span>:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="email" class="form-control-sm" data-ng-model="mail" id="userid" name="email"  placeholder="Enter EmailId" required="" autofocus/></div>
<span style="color:red; font-size:14px" ng-show="loginform.email.$dirty && loginform.email.$invalid" ng-show="noid">

</span></br>

<div>Password<span style="color:red">*</span>: &nbsp;<input type="password" class = "form-control-sm" data-ng-model="pwd" id="password" name="pass" placeholder="Enter Password" required=""/></div>
</br>

<input type="button" ng-click="logincheck()"  value="Submit" class="btn btn-xs btn-primary">

</form>
</div>

</div>
</body>
</html>




ctrl.js

inciteapp.controller("pizzaController", ['$scope', '$http', function ($scope, $http)
{
            'use strict';

            var vm = this;

            $scope.brand = {name: ""};
            $http.defaults.useXDomain = true;
            $scope.logincheck = function () {
            var myRequest = new XMLHttpRequest();
                $.param = JSON.stringify({
                "emailId":$scope.mail,
                "brandName":$scope.name,
                "password":$scope.pwd

            });
                var user = JSON.parse($.param);

            $http({
                url:'http://182.xx.xxx.xxx:9090/incite-merchant/connects/login',
                method: 'POST',
                data: user,
                withCredentials : true,
                /*xhr.credentials = crossdomain;*/
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Access-Control-Allow-Origin': '*' | 'http://192.xxx.x.xxx:8080',
                    'Access-Control-Allow-Credentials': 'true',
                    'Access-Control-Allow-Headers': 'Origin, Authorization, Content-Type, X-Requested-With, Timeout, X-CSRF-Token, Accept, Accept-Version, Content-Length, Content-MD5,',
                    'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
                    'Access-Control-Expose-Headers': 'DAV, content-length, Allow',
                    'Access-Control-Max-Age': '3600'

                }
            }).success(function (response, headers, config, status) {
                console.log(user);
                console.log(response);

                    if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                        header( "HTTP/1.1 200 OK" );
                        exit();
                    }*/

                if(response.response === success)
                {
                    window.location.href = "../11.06.15 Email login/welcome.html";
                }
            }).error(function (response, headers, config, status) {
                if(response == 200)
                {
                    window.location.href = "../11.06.15 Email login/welcome.html";
                }
                if(response === null)
                {
                    alert("Configure the server response!");
                }
                console.log(user);
            })
        }
}]);

【问题讨论】:

  • 您添加到 $http 的标头必须在服务器端进行配置。不是客户端。 link

标签: java javascript angularjs cors credentials


【解决方案1】:

必须在服务器端设置“访问控制”标头以响应浏览器未请求的响应请参阅How to enable CORS in AngularJs

PS。还要检查您的代码是否有语法错误。 JS 中似乎有一些 cmets 没有注释开始标记,而在 html 中您应该使用 &lt;br/&gt; / 必须在末尾。

【讨论】:

    【解决方案2】:

    在 Angular 方面绝对没有什么可做的!!你可能读到你必须在你的应用配置中添加这样的东西:

    myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }
    ]);
    

    不要!也许它仅对旧版本的 Angular 或非常特殊的后端有用。所以你的问题来自你的后端,而不是来自 angularJs

    【讨论】:

      【解决方案3】:

      这是因为您的后端拒绝跨域请求。这个问题有多种解决方案,但归结为过滤您的请求并允许 preflight。不要忘记注册您的过滤器。

      例如:

      public class CorsFilter extends OncePerRequestFilter {
      
              @Override
              protected void doFilterInternal(HttpServletRequest request,
                      HttpServletResponse response, FilterChain filterChain)
                      throws ServletException, IOException {
      
                  response.setHeader("Access-Control-Allow-Origin", "*");
                  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
                  response.setHeader("Access-Control-Max-Age", "3600");
                  response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
      
                  if (request.getMethod().equals("OPTIONS")) {
                      try {
                          response.getWriter().print("OK");
                          response.getWriter().flush();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  } else {
                      filterChain.doFilter(request, response);
                  }
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 2019-02-19
        • 2014-06-22
        • 2021-08-11
        • 1970-01-01
        • 2014-02-12
        • 2018-07-22
        • 2017-01-20
        • 1970-01-01
        • 2013-12-24
        相关资源
        最近更新 更多