1
votes

I'm facing problem with CORS requests in AngularJS while calling web services but the same service able to call by using jQuery.

Note: From server side we are receiving header "Access-Control-Allow-Origin:*" and these services are running fine in jQuery application.

Here I'm posting my AngularJS code as well as jQuery code.

AngularJS:

$http({
        method: 'POST',
        url:  $rootScope.host + "UserLogin",
        //headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: {
            "uname": $scope.uname,
            "password": $scope.password
        },
    }).then(function (success) {
                $scope.loginDetails = success;
                console.log($scope.loginDetails);
    }),function (error){
            console.log(error);
});

If I pass the header like headers: { 'Content-Type': 'application/x-www-form-urlencoded' } able to ping the service but my request is not going in JSON format.

If I change the header to 'Content-Type': 'application/json', getting

XMLHttpRequest cannot load https://XXXX.XXXX.in/XXXXAPI/UserLogin.

Response to preflight request doesn't pass access control check:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://170.11.0.61' is therefore not allowed access.

I don't know what is the reason for this error.

$.ajax({
    url: BASE_URL + "UserLogin",
    type: "POST",
    xhrFields: {withCredentials: true},
    data: {
        "uname": uname,
        "password": password
    },
    cache: false,
    success: function (result, textStatus, request) {
        console.log(result);
    },
    error: function (e) {
        console.log("Error in login service call:"+JSON.stringify(e));
    }
});

This jQuery is sending my request in the json format.

1

1 Answers

0
votes

Try to pass headers like

headers: { 'Content-Type': 'application/json' }