Solving CORS when posting in angularJs using $HTTP with credentials

3.9k views Asked by At

On click of the submit button, the emailId and password is parsed and sent through the $http method.

The Server is refusing to accept the Api call as the server and client have different IP and port.

The server response header has the java CORS filter enabled.

The server is running on STS and hosted on Apache Tomcat, the front-end is hosted on web storm server.

DB is connected through @requestbody maps in java controller.

I've included all possible combination of headers on client-side possible, but it hasn't helped.

I tried with content type : 'application/x-www-form-urlencoded' aswell as text/html and application/json. Nothing seems to work.

The error that the server shoots up is : "XMLHttpRequest cannot load http://182.72.xxx.xxx:9090/incite-merchant/connects/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.x.xxx:8080' is therefore not allowed access."

Looking forword for help.

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);
            })
        }
}]);
3

There are 3 answers

0
Michael On

The 'Access Control' headers have to be set on the server side to the response not on request by the browser See How to enable CORS in AngularJs

PS. Also check your code for syntax errors. There seem to be some comments left-over in the JS without a comment start tag and in the html you should use <br/> the / has to be at the end.

0
FlavienBert On

There is absolutely nothing to do on the Angular side!! You may read that you have to add stuff like this in your app config:

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

Don't! Maybe it was useful for older versions of Angular or for very special backends only. So your issue comes from your backend but not from angularJs

0
skubski On

This is because your back-end is refusing cross-domain requests. There are several solutions to this problem but it all boils down to filtering your request and allowing the preflight. Don't forget to register your filter.

e.g.:

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

    }