[javascript] AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

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"
              }
  ];

})();

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'.

What may be going wrong? Is it a path issue for product-color.html?

All my three files are in the same root folder C:/user/project/

This question is related to javascript html angularjs xmlhttprequest

The answer is


VERY SIMPLE FIX

  1. Go to your app directory
  2. Start SimpleHTTPServer


In the terminal

$ cd yourAngularApp
~/yourAngularApp $ python -m SimpleHTTPServer

Now, go to localhost:8000 in your browser and the page will show


The Reason

You are not opening the page through a server, like Apache, so when the browser tries to obtain the resource it thinks it is from a separate domain, which is not allowed. Though some browsers do allow it.

The Solution

Run inetmgr and host your page locally and browse as http://localhost:portnumber/PageName.html or through a web server like Apache, nginx, node etc.

Alternatively use a different browser No error was shown when directly opening the page using Firefox and Safari. It comes only for Chrome and IE(xx).

If you are using code editors like Brackets, Sublime or Notepad++, those apps handle this error automatically.


there is a chrome extension 200ok its a web server for chrome just add that and select your folder


My problem was resolved just by adding http:// to my url address. for example I used http://localhost:3000/movies instead of localhost:3000/movies.


  1. Install the http-server, running command npm install http-server -g
  2. Open the terminal in the path where is located the index.html
  3. Run command http-server . -o
  4. Enjoy it!

I would add that one can also use xampp, mamp type of things and put your project in the htdocs folder so it is accessible on localhost


Navigate to C:/user/project/index.html, open it with Visual Studio 2017, File > View in Browser or press Ctrl+Shift+W


Adding to @Kirill Fuchs excellent solution and answering @StackUser's doubt - while starting the http-server, set the path till the app folder only, NOT till the html page! http-server C:\location\to\app and access index.html under app folder


If you are using this in chrome/chromium browser(ex: in Ubuntu 14.04), You can use one of the below command to tackle this issue.

ThinkPad-T430:~$ google-chrome --allow-file-access-from-files
ThinkPad-T430:~$ google-chrome --allow-file-access-from-files fileName.html

ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files
ThinkPad-T430:~$ chromium-browser --allow-file-access-from-files fileName.html

This will allow you to load the file in chrome or chromium. If you have to do the same operation for windows you can add this switch in properties of the chrome shortcut or run it from cmd with the flag. This operation is not allowed in Chrome, Opera, Internet Explorer by default. By default it works only in firefox and safari. Hence using this command will help you.

Alternately you can also host it on any web server (Example:Tomcat-java,NodeJS-JS,Tornado-Python, etc) based on what language you are comfortable with. This will work from any browser.


This issue is not happening in Firefox and Safari. Make sure you are using the latest version of xml2json.js. Because i faced the XML parser error in IE. In Chrome best way you should open it in server like Apache or XAMPP.


If for whatever reason you cannot have the files hosted from a webserver and still need some sort of way of loading partials, you can resort to using the ngTemplate directive.

This way, you can include your markup inside script tags in your index.html file and not have to include the markup as part of the actual directive.

Add this to your index.html

<script type='text/ng-template' id='tpl-productColour'>
 <div class="list-group-item">
    <h3>Hello <em class="pull-right">Brother</em></h3>
</div>
</script>

Then, in your directive:

app.directive('productColor', function() {
      return {
          restrict: 'E', //Element Directive
          //template: 'tpl-productColour'
          templateUrl: 'tpl-productColour'
      };
   }
  );

If you are running server already, don't forget to use http:// in the API call. This might cause a serious trouble.


RootCause:

File protocol does not support cross origin request for Chrome

Solution 1:

use http protocol instead of file, meaning: set up a http server, such as apache, or nodejs+http-server

Sotution 2:

Add --allow-file-access-from-files after Chrome`s shortcut target, and open new browse instance using this shortcut

enter image description here

Solution 3:

use Firefox instead


You have to open chrome using the following flag Go to run menu and type "chrome --disable-web-security --user-data-dir"

Make sure all the instances of chrome are closed before you use the flag to open chrome. You will get a security warning that indicates CORS is enabled.


I had the same issue. after adding below code to my app.js file it fixed.

var cors = require('cors')
app.use(cors());

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to xmlhttprequest

What is difference between Axios and Fetch? Basic Authentication Using JavaScript XMLHttpRequest module not defined/found loading json data from local file into React JS AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource Edit and replay XHR chrome/firefox etc? AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https jQuery has deprecated synchronous XMLHTTPRequest Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Sending a JSON to server and retrieving a JSON in return, without JQuery