問題描述
我有一個非常簡單的 Angular js 應用程序的三個文件
I have three files of a very simple angular js application
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 的包含時,我就開始收到此錯誤:
I started getting this error as soon as I entered an include of product-color.html using custom directive named productColor:
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 的路徑問題?
What may be going wrong? Is it a path issue for product-color.html?
我的三個文件都在同一個根文件夾C:/user/project/
All my three files are in the same root folder C:/user/project/
推薦答案
出現此錯誤是因為您只是直接從瀏覽器打開 html 文檔.要解決此問題,您需要從網絡服務器提供代碼并在 localhost 上訪問它.如果您有 Apache 設置,請使用它來提供文件.一些 IDE 內置了 Web 服務器,例如 JetBrains IDE、Eclipse...
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
如果您有 Node.Js 設置,那么您可以使用 http-server.只需運行 npm install http-server -g
即可在終端中使用它,例如 http-server C:location oapp
.
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g
and you will be able to use it in terminal like http-server C:location oapp
.
這篇關于AngularJS 錯誤:跨源請求僅支持協議方案:http、data、chrome-extension、https的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!