Raanan Sampanth
Raanan Sampanth

Reputation: 107

Can't access JSON file exists in the same folder : AngularJS

I try to use a JSON file, JSON file exists in the same folder with my HTML file.

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){
        $http.get('countries.json').success(function(data) {
          $scope.countries = data;
        });
      });
    </script>
  </head>
  <body ng-controller="CountryCtrl">
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
      </tr>
      <tr ng-repeat="country in countries">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
      </tr>
    </table>
  </body>
</html>

But when I load my HTML file I get a console error saying:

XMLHttpRequest cannot load file://countries.json/. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Upvotes: 0

Views: 1460

Answers (2)

baklazan
baklazan

Reputation: 819

You can't load other files from your javascript on localhost, due to security issues. Try running your page in http server.

If you have python you can just write python -m SimpleHTTPServer 8000 in your console where working directory is your source folder and then open http://localhost:8000 .

Upvotes: 1

notAChance
notAChance

Reputation: 1430

What you can do is change $http.get('countries.json').success(function(data) { to this

$http.get("http://localhost:9009/yourFolderName/countries.json").then(function (data) {

assuming you are running http local server on port 9009.

Upvotes: 1

Related Questions