我们假设这段代码位于不同的域(服务器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服务器上运行它。但后来,我收到了这个错误:
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
如何修改我的控制器以与CORS兼容。
答案 0 :(得分:1)
这是检测浏览器对CORS支持的方式 。这些浏览器支持它:
//Detect browser support for CORS
if ('withCredentials' in new XMLHttpRequest()) {
/* supports cross-domain requests */
document.write("CORS supported (XHR)");
} else {
if (typeof XDomainRequest !== "undefined") {
//Use IE-specific "CORS" code with XDR
document.write("CORS supported (XDR)");
} else {
//Time to retreat with a fallback or polyfill
document.write("No CORS Support!");
}
}
&#13;