Angular js: cross-origin request blocked: same origin policy forbids reading remote resource
I am getting this error when I try to post data using $ http.post () in Angular Js.
Cross-Origin Request Blocked: The Same Origin Policy prevents reading the remote resource at {{post url}}. This can be fixed by moving the resource to the same domain or by enabling CORS.
This is my code:
var ionicAppControllers = angular.module('ionicAppControllers', []);
ionicAppControllers.config(function($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
//Remove the header containing XMLHttpRequest used to identify ajax call
//that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
ionicAppControllers.controller('createItemCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.parts = [];
$scope.add = function() {
$scope.parts.push({
id: '',
code: '',
description: ''
});
};
$scope.submitItemForm = function(isValid) {
if (isValid) {
$scope.postdata = {};
$scope.postdata.item = $scope.item;
$scope.postdata.description = $scope.description;
for (var i in $scope.parts)
{
for (var j in $scope.parts[i])
{
if (j == '$$hashKey')
{
delete($scope.parts[i][j]);
//console.log(j);
}
}
}
$scope.postdata.parts = $scope.parts;
console.log($scope.postdata);
$http({
method: 'POST',
url: 'URL',
data: $scope.postdata, // pass in data as strings
headers: {'Content-Type': 'application/json'}
}).success(function(data) {
if (data.success)
{
alert('sucess');
}
else
{
alert('fail');
}
});
}
};
$scope.add();
}]);
source to share
This has nothing to do with Angular. The Server app needs to enable or allow a request generated from your Angular app that is hosted or running on any machine. If your application is running on localhost. Use the CORS chrome extension. If it's from another server. let's say www.example.com.
The server code shouldn't change anything in the perspective on the front panel.
Please refer to this link. http://enable-cors.org/server.html
source to share
if you are using ASP MVC and getting jsonresult you have to add this xml code to web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
source to share