0

I have tried accepted answers in stackoverflow for this problem. In angularjs,when i send a post request to local Api it works.but when i change to cross domain api it does not work.

This is my code

 var myapp = angular.module('myApp',['ngRoute','http-auth-interceptor'])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }])
     .factory('featuresData', function ($http) {
        return{          
            doCrossDomainGet: function(data) {
                return $http({
                    url:'http://example.com/api/login',
                     type: "POST",
        crossDomain: true,
        data: JSON.stringify({"username":"test_teacher" , "password":"123"}),
        contentType:  'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            console.log(response);


        },
        error: function (xhr, status) {
            alert("error");
        }
                })
            }        
        }
});

I am getting this message in console:

XMLHttpRequest cannot load example.com/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost'; is therefore not allowed access. The response had HTTP status code 405.

The Api works fine from Android,Ios client apps and from CURL

curl command 

curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://example.com/api/login -d '{"username":"test_teacher","password":"123"}'

curl output

{"username":"test_teacher","roles":["ROLE_TEACHER"],"access_token":"7q8dcreo5bngk32jq8nmefrfgp6nope2"}
Nisham Mahsin
  • 1,389
  • 5
  • 17
  • 41
  • have you tried adding access to allow origins (for requests) at your server end? – V31 Mar 22 '15 at 18:22
  • Are you sure, that your "example.com" uri accepts POST -Data? 405 means, "Method not allowed", maybe they only accept GET/PUT? Did you analyze the response header? It should state, what methods are allowed – kfis Mar 22 '15 at 18:22
  • @kfis POST method is allowed on server , but I am not able to get any response from server. I am getting this message in console ` XMLHttpRequest cannot load http://example.com/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.` – Nisham Mahsin Mar 22 '15 at 18:34
  • @V31 Is it possible to force angular to make cross-domain requests , even when access to allow-origins is not set in server? – Nisham Mahsin Mar 22 '15 at 18:40
  • you can try `dataType: "jsonp",` – Grundy Mar 22 '15 at 18:46
  • can you describe which server stack you are using? this CORS issue is related to your server, so knowing what you are using is necessary to answering the question properly. – Claies Mar 22 '15 at 18:56
  • @Claies we are using grails server .android,ios client apps are able to consume this api. – Nisham Mahsin Mar 22 '15 at 19:04
  • According to this answer, you can only solve the issue on the server, not on the angular client side http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin You have to adjust the server response header – kfis Mar 22 '15 at 22:20
  • The API works from your android and other stuff, because they are not bound to the CORS-Restriction, that are built in into the browsers. – kfis Mar 22 '15 at 22:22

2 Answers2

0

Your angular app and your backend grails api are not on same domain. So when you make an api call from angular to grails backend, it is actually a cross domain ajax call. You cant make cross domain ajax calls unless you have configured your app accordingly.

See cors plugin - it will help you support cors.

Sudhir N
  • 3,890
  • 1
  • 20
  • 31
0

I faced the similar issue ,after a long research i found a simple solution which is working for me.

Remove all the CORS related settings in web.config

like

 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>

Just add these two lines in the WebAPIconfig.cs

// Web API routes

var cors = new EnableCorsAttribute("", "", "*"); config.EnableCors(cors);

and your post request from angular

 Factory.postData = function (data) {
        var request = $http({
            method: "POST",
            url: urlBase+'api/url',
            data: data,
            headers: {
                "Content-Type": "application/json"
            }
        });
        return request;
    }