Han Che Han Che - 1 month ago 7
Javascript Question

AngularJS not working in Chrome (Mac and Windows) but in Safari

I'm starting to learn some AngularJS when I stumbled on a strange issue.

The following code is from a online tutorial Github.

While it works perfectly on Safari (MAC) it won't load on Chrome. Same thing happens when I try opening it up in Chrome on Windows.

Any ideas why Chrome won't work? Also Chrome won't load AngularJS Admin Templates (Metronics for example).

Note that these codes somehow don't work when I launch them from the folders but they do work (e.g. demo in tutorial or online preview of metronics angular)

Cheers!

Error message

XMLHttpRequest cannot load file:///Users/aavelyn/Desktop/untitled%20folder/articles.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.(anonymous function) @ angular.js:10413

The json file is

[
{"id": "1", "name": "Pizza Vegetaria", "price": 5 },
{"id": "2", "name": "Pizza Salami", "price": 5.5 },
{"id": "3", "name": "Pizza Thunfisch", "price": 6 },
{"id": "4", "name": "Aktueller Flyer", "price": 0 }
]




'use strict';

angular.module('tutorialApp', [])
.controller('ArticlesCtrl', function($scope, $http) {
$http.get('articles.json').then(function(articlesResponse) {
$scope.articles = articlesResponse.data;
});
});

<html ng-app="tutorialApp">

<head>
<meta charset="utf8" />
<title>AngularJS Tutorial</title>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">

<form>
<input type="text" ng-model="search">
<p ng-show="search">Du suchst gerade nach: {{search}}</p>
</form>

<table class="table" ng-controller="ArticlesCtrl">
<tr ng-repeat="article in articles | filter:search">
<td>{{article.id}}</td>
<td>{{article.name}}</td>
<td>{{article.price}}</td>
</tr>
</table>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app.js"></script>
</body>

</html>




Answer

Browser's have security measures in place to prevent loading files off the file system via ajax. If you want to run in locally, you need to have some kind of server running locally. There are many very simple servers you can install and run locally. For example, if you have nodejs installed, you can install node-static with the following from your command line:

npm install -g node-static

Then, CD into the directory where your files are and just run:

static

A simple server will be start running at http://localhost:8080 with your files.

Install nodejs from nodejs.org. Info about node-static is at https://github.com/cloudhead/node-static

Comments