2

My Sever side is php/mysql.

I am making Ajax call in webservice of another domain(Which have access control enabled for *)

    var postUrl = "http://logical-brains.com/elance_clone/test_login.php";
    var postData = {username : "tanmoy" , password : "123456"};

I tried by Simple jQuery :

 $.ajax({
  type: "POST",
  url: postUrl,
  data: postData,
   dataType: "json",
  crossDomain: true,
  success: function(data){ console.log(JSON.stringify(data)); }
}); 

It worked fine and I got Status Code:200 OK with expected result.

BUT When I am trying by AngularJs , getting below Error :

XMLHttpRequest cannot load http://logical-brains.com/elance_clone/test_login.php. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. 

AngularJs Code :

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

myApp.controller('MainCtrl', function($scope, $http) {
    var postUrl = "http://logical-brains.com/elance_clone/test_login.php";
    var postData = {username : "tanmoy" , password : "123456"};
    $http({
        url: postUrl,
        method: "POST",
        data: postData,
         crossDomain: true
    })
    .then(function(result) {
            console.log("Success", result);
            $scope.someVal = JSON.stringify(result);
        }, 
        function(response) { // optional
            console.log("error "+response);
        }
    ); }; });

1 Answer 1

6

I was in the problem. by deep search i get .. For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server. so if server does not allow it will throw errors. by default angular content type is application/json which is trying to send a OPTION request. but jquery default is application/x-www-form-urlencoded; charset=UTF-8 so in your case for jquery is working and for angular it is not. try to overwrite angular default header . or allow it in server end. here is angular sample:

$http.post(url,data,{
              headers : {
                'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
            }

    });

see http://api.jquery.com/jquery.ajax/ content-type for detail

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.