当前位置: 首页 > 知识库问答 >
问题:

AngularJS错误:交叉源请求仅支持协议方案:http、data、chrome-extension、https

卫烨
2023-03-14

我有一个非常简单的angular js应用程序的三个文件

index.html

<!DOCTYPE html>
<html ng-app="gemStore">
  <head>
    <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js'></script>
    <script type="text/javascript" src="app.js"></script>
  </head>

  <body ng-controller="StoreController as store">
      <div class="list-group-item" ng-repeat="product in store.products">
        <h3>{{product.name}} <em class="pull-right">{{product.price | currency}}</em></h3>
      </div>

  <product-color></product-color>
  </body>
</html>

产品-color.html

<div class="list-group-item">
    <h3>Hello <em class="pull-right">Brother</em></h3>
</div>

应用程序JS

(function() {
  var app = angular.module('gemStore', []);

  app.controller('StoreController', function($http){
              this.products = gem;
          }
  );

  app.directive('productColor', function() {
      return {
          restrict: 'E', //Element Directive
          templateUrl: 'product-color.html'
      };
   }
  );

  var gem = [
              {
                  name: "Shirt",
                  price: 23.11,
                  color: "Blue"
              },
              {
                  name: "Jeans",
                  price: 5.09,
                  color: "Red"
              }
  ];

})();

当我使用名为ProductColor的自定义指令输入product-color.html的include时,就开始出现此错误:

XMLHttpRequest cannot load file:///C:/product-color.html. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
angular.js:11594 Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/product-color.html'.

可能出了什么问题?这是product-color.html的路径问题吗?

我的三个文件都在同一个根文件夹中c:/user/project/

共有2个答案

赵渊
2023-03-14

非常简单的修复

  1. 转到应用程序目录
  2. 启动SimpleHttpServer


在终端中

$ cd yourAngularApp
~/yourAngularApp $ python -m SimpleHTTPServer

现在,在浏览器中转到localhost:8000,页面将显示

赏彭薄
2023-03-14

发生此错误是因为您只是直接从浏览器打开html文档。要解决这个问题,您需要从Web服务器提供代码,并在localhost上访问它。如果您安装了Apache,请使用它为您的文件提供服务。有些IDE已经内置了web服务器,比如JetBrains IDE、Eclipse...

如果您安装了node.js,那么就可以使用HTTP-Server。只需运行npm install http-server-g,您就可以像http-serverc:\location\to\app那样在终端中使用它。

 类似资料: