【发布时间】:2017-09-06 02:52:19
【问题描述】:
假设这段代码位于不同的域(服务器 A)中,我想在本地机器(服务器 B)上工作。
HTML 代码:
<html ng-app="myApp">
<body ng-controller="empInfoCtrl as employeeList">
<p>Employee Information</p>
<section>
<ul>
<p ng-show="!employeeList.fileError" ng-repeat="employee in employeeList.employees"> {{employee.id}} - {{employee.jobTitleName}}</p>
</ul>
</section>
<p style="color:red" ng-show="employeeList.fileError"> <b>Response:</b> {{employeeList.employees}} </p>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
控制器(JavaScript 文件):
var app = angular.module("myApp", []);
app.controller('empInfoCtrl', function ($http) {
var employeeList = this;
employeeList.fileError = false;
$http.get('employees.json')
.then(function (response) {
employeeList.employees = response.data.empdata;
}, function (response) {
employeeList.fileError = true;
employeeList.employees = response.statusText;
})
});
如果我想通过不同的域访问它怎么办?我尝试在本地机器的 http-server 上运行它。但是后来,我收到了这个错误:
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
如何修改我的控制器以与CORS 兼容。
【问题讨论】:
-
控制器中无能为力。它不依赖于客户端代码。已经有一堆关于 SO 的 CORS 问题解释了关于服务器端可以做什么。
-
CORS 对客户端是透明的。 服务器 必须支持 CORS。如果服务器确实支持 CORS,则无需更改任何内容。如果服务器不支持 CORS,则您无法更改任何内容(除非您拥有服务器 - 是吗?)。您可能会发现我在 How does Access-Control-Allow-Origin header work? 上的回答是一个很好的起点。
-
@apsillers 太棒了!现在我明白了:)
标签: javascript angularjs cors