2017-04-10 6 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-serverでそれを実行しようとしました。私はCORSと互換性があるために、私のコントローラを変更するにはどうすればよい

'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'null' is therefore not allowed access. 

:しかし、その後、私はこのエラーを取得しました。

+1

コントローラで行うことは何もありません。クライアント側のコードに依存しません。すでにCORSの質問には、サーバー側に関して何ができるのかを説明するものがあります。 – estus

+2

CORSはクライアントに対して透過的です。 *サーバー*はCORSをサポートする必要があります。サーバーがCORSをサポートしている場合は、変更する必要はありません。サーバーがCORSをサポートしていない場合は、変更することはできません(サーバーを所有している場合を除きます)。あなたは、[Access-Control-Allow-Originヘッダーの仕組みはどういうのですか](http://stackoverflow.com/a/10636765/710446)の回答を参考にしてください。 – apsillers

+0

@apillers great!今私は理解した:) – Chip

答えて

1

これは、CORS のブラウザサポートを検出する方法です。

  • クロム3+
  • のFirefox 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!"); 
 
    } 
 
}
:それは、これらのブラウザでサポートされています

関連する問題