一尘不染

AngularJS错误:仅协议方案支持跨源请求:http,数据,chrome扩展名,https

angularjs

我有一个非常简单的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>

product-color.html

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

app.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的包含内容后,我就开始出现此错误:

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/


阅读 239

收藏
2020-07-04

共1个答案

一尘不染

发生此错误是因为您只是直接从浏览器中打开html文档。要解决此问题,您需要从网络服务器提供代码并在localhost上访问它。如果您有Apache设置,请使用它来提供文件。一些IDE已内置Web服务器,例如JetBrains
IDE,Eclipse …

如果您已安装Node.Js,则可以使用http-server。只需运行npm install http-server -g,您就可以在像这样的终端中使用它http-server C:\location\to\app

2020-07-04