更新:这是我在行console.log
=data之前执行$scope.Host时所遇到的错误;
XMLHttpRequest cannot load http://..... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52029' is therefore not allowed access.
我试图调用一个返回JSON数据的API,我是AngularJS的初学者,我想要做的是调用一个API并非常简单地显示数据。
我的HTML文件:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My AngularJS App</title>
<script src="../scripts/angular.js"></script>
</head>
<body>
<div data-ng-app="MyModule">
<table class="table" data-ng-controller="MyModuleCtrl">
<tr>
<th>
FirstName
</th>
<th>
MiddleName
</th>
<th>
LastName
</th>
<th>
Email
</th>
<th>
Active
</th>
</tr>
<tr>
<td>
{{Host.FirstName}}
</td>
<td>
{{Host.MiddleName}}
</td>
<td>
{{Host.LastName}}
</td>
<td>
{{Host.Email}}
</td>
<td>
{{Host.Active}}
</td>
</tr>
</table>
</div>
<script src="../scripts/MyApp/App.js"></script>
</body>
</html>
App.js文件:
var MyModule = angular.module("MyModule", []);
MyModule.factory('MyHttpService',
['$http', function ($http) {
return {
getAll: function () {
return $http.get('http://api.host.com/host'); //it returns json data
}
};
}]);
MyModule.controller('MyModuleCtrl', ['$scope', '$http', '$window', 'MyHttpService',
function ($scope, $http, $window, MyHttpService) {
load();
function load() {
MyHttpService.getAll().success(function (data) {
$scope.Host = data;
}
);
}
}]);
发布于 2014-05-07 05:16:07
为了给出一个答案:
$http.get('http://api.host.com/host');
是您获得CORS/xhr异常的原因。因为该域与您的角应用程序不同,所以您的浏览器将其视为CORS请求。您有两个选择-处理服务器上的CORS请求,或设置相同的域并删除CORS问题。如果选择选项1,请参见设置允许您的请求的CORS响应头。如果您选择选项2(向localhost:发出请求),您所拥有的代码应该正确工作。
我回答了this question,我详细介绍了CORS的工作原理/浏览器如何处理CORS请求。
https://stackoverflow.com/questions/23483999
复制相似问题