简体   繁体   中英

Getting an error while sending an ajax request, with Angular, to get .json file?

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?

Host application to localhost or try on other browsers.

For chrome you can allow this by:

chrome.exe --allow-file-access-from-files 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM