【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'file://' 不允许访问。
【发布时间】:2014-10-07 03:01:01
【问题描述】:

我有一个 node.js 服务器在我的计算机上本地运行。我正在使用 js-code 开发 html 页面:

var MainController = function($scope, $http) {

    var onCountComplete = function(response) {
        $scope.count = response.data;
    };

    var onError = function(reason) {
        $scope.error = "Could not fetch data";
    };

    $http.get("http://localhost:1337/api/count")
        .then(onCountComplete, onError);

    $scope.message = "hello";
};

我在运行此代码时遇到错误:

XMLHttpRequest 无法加载 http://localhost:1337/api/count。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,Origin 'file://' 不允许访问。

我尝试使用 --allow-file-access-from-files 键启动 Chrome,但没有帮助。有没有办法在开发过程中避免这个错误?

【问题讨论】:

  • 您的 api 服务器上是否启用了 CORS?
  • 你可以尝试在服务器端设置Access-Control-Allow-Origin: *响应头吗?
  • 你在做跨域请求,这就是问题所在。您必须将服务器和客户端放在同一个域中或在服务器上启用 CORS
  • 在 node.js 的情况下我该怎么做(在服务器上启用 CORS)?
  • 如果您使用 Express,this link 可能会有所帮助。

标签: javascript angularjs


【解决方案1】:

如果您使用的是 Apache,则可以尝试此解决方案。这在一些小项目上对我有用。只需将这些行添加到您的 .htaccess 文件中。虽然根据需要进行自定义,但我下面的示例相当宽松,例如,您可能只需要 POST 或特定来源。

Header set Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "GET, POST, OPTIONS, DELETE"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type"

【讨论】:

    猜你喜欢
    • 2013-12-24
    • 2017-02-04
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2018-10-15
    • 2014-03-13
    相关资源
    最近更新 更多