2017-04-10 37 views
0

假設這段代碼位於不同的域(服務器A),並且我想在本地計算機(服務器B)上工作。如何使CORS兼容模塊?

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兼容。

+1

在控制器中沒有什麼可以做的。它不依賴於客戶端代碼。 SO上已經有了一堆CORS問題,解釋了服務器端可以做些什麼。 – estus

+2

CORS對客戶是透明的。 *服務器*必須支持CORS。如果服務器不支持CORS,則不需要更改。如果服務器不支持CORS,則沒有什麼可以改變的(除非你擁有服務器 - 是嗎?)。您可能會在[Access-Control-Allow-Origin頭文件如何工作?](http://stackoverflow.com/a/10636765/710446)上找到我的答案,這是一個很好的起點。 – apsillers

+0

@apsillers太棒了!現在我明白了:) – Chip

回答

1

這就是您如何檢測對CORS 的瀏覽器支持。它支持在這些瀏覽器:

  • 鉻3+
  • 的火狐3.5
  • 歌劇12+
  • 的Safari 4+
  • 的Internet Explorer 8+

//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!"); 
 
    } 
 
}