【问题标题】:how to make a module CORS compatible?如何使模块CORS兼容?
【发布时间】: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


【解决方案1】:

这是检测浏览器对 CORS 的支持的方式 .这些浏览器都支持它:

  • 铬 3+
  • 火狐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!");
  }
}

【讨论】:

    猜你喜欢
    • 2012-05-28
    • 2020-04-22
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-11
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多