当我尝试使用Angular Js中的$ http.post()发布数据时,我收到此错误。
阻止跨源请求:同源策略禁止在{{post url}}读取远程资源。这可以通过将资源移动到同一域或启用CORS来解决。
这是我的代码:
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();
}]);
答案 0 :(得分:2)
这与Angular无关。 Server应用程序应启用或允许从任何计算机上托管或运行的Angular应用程序生成的请求。如果您在localhost中运行您的应用程序。使用CORS扩展名进行chrome。如果它来自其他服务器。比方说www.example.com。
前端透视图中的服务器代码必须不做任何更改。
答案 1 :(得分:-2)
如果您使用ASP MVC并获取jsonresult,则必须在web.config中添加此xml代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>