0

Let's say this piece of code is in a different domain (Server A) and I wanted to work on my local machine (Server B).

HTML Code:

<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>

Controller (JavaScript file):

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;
        })
});

What if I want to access it through a different domain? I tried running it on my local machine's http-server. But then, I was getting this error:

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

How do I modify my Controller in order to be compatible with CORS.

coderpc
  • 4,119
  • 6
  • 51
  • 93
  • 1
    There's nothing you can do in controller. It doesn't depend on client side code. There are already a bunch of CORS questions on SO that explain what can be done regarding server side. – Estus Flask Apr 10 '17 at 22:19
  • 2
    CORS is transparent to the client. The *server* must support CORS. If the server does support CORS, there is nothing you need to change. If the server does not support CORS, there is nothing you can change (unless you own the server -- do you?). You might find my answer on [How does Access-Control-Allow-Origin header work?](http://stackoverflow.com/a/10636765/710446) to be a good starting point. – apsillers Apr 10 '17 at 22:19
  • @apsillers great! now I understood :) – coderpc Apr 10 '17 at 22:48

1 Answers1

1

This is how you Detect browser support for CORS . It is supported in the these browsers:

  • Chrome 3+
  • Firefox 3.5+
  • Opera 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!");
  }
}
scriobh
  • 868
  • 10
  • 25