1

I have the .json file that was created by backend. Now I am trying to make an ajax request using Angular.js so my frontend could use the data from my .json file.

Here is the path to my .json file:

C:\Users\Mykhaylo Vayvala\Desktop\carBuyer\topCarObj.json

Here is my html file:

<!DOCTYPE html>
<html ng-app="MyApp">
    <head>
        <title>Top cars</title>
    <head>
    <body ng-controller="PostsCtrl">
      <p>{{posts}}</p>
        <script type="text/javascript" src="angular.min.js"></script>
        <script type="text/javascript" src="carApp.js"></script>
    </body>
</html>

Here is my JavaScript file using Angular.js:

var app = angular.module("MyApp", []);

app.controller("PostsCtrl", function($scope, $http) {
  $http.get('topCarObj.json').
    success(function(data, status, headers, config) {
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      alert("AJAX failed")
    });
});

When I run my html file in the browser I get the following error in the console:

XMLHttpRequest cannot load file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/topCarObj.json. Cross origin requests are only supported for HTTP. angular.min.js:78
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/topCarObj.json'.
    at Error (native)
    at file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:78:466
    at v (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:73:464)
    at g (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:71:294)
    at I (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:100:144)
    at I (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:100:144)
    at file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:101:308
    at k.$eval (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:112:32)
    at k.$digest (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:109:121)
    at k.$apply (file:///C:/Users/Mykhaylo%20Vayvala/Desktop/carBuyer/angular.min.js:112:362) 

What have I done wrong and how can I fix that?

Michael
  • 15,386
  • 36
  • 94
  • 143
  • You can't use XMLHttpRequest to get files on localhost with absolute path. You must use **http://...**, i.e., **http:// localhost:8080/file.json**. – fntneves Aug 31 '14 at 12:07

1 Answers1

2

Host application to localhost or try on other browsers.

For chrome you can allow this by:

chrome.exe --allow-file-access-from-files 
Yogesh
  • 3,394
  • 9
  • 31
  • 46
  • @MichaelVayvala you have to install server like wamp or its alternatives and then host it there. – Yogesh Aug 31 '14 at 12:15
  • @MichaelVayvala for now you can just open chrome with above command http://stackoverflow.com/questions/4208530/xmlhttprequest-origin-null-is-not-allowed-access-control-allow-origin-for-file – Yogesh Aug 31 '14 at 12:16