【发布时间】:2014-12-26 07:40:53
【问题描述】:
当我尝试在 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();
}]);
【问题讨论】:
-
不知道是什么...只是为了消除错误而写...
标签: angularjs angularjs-directive angularjs-scope cors