0

I am trying to fetch data in AngularJS using Http Get request. I have created a separate controller.js file where I have implemented Http get service.

I have created a database.json file within the app.When I am trying to run my app on http-server, I am unable to fetch data from the data file created.

I am getting the following error in my console.

enter image description here

index.html:

<!DOCTYPE html>
<html>

  <meta charset="utf-8">
  <title>AngularJS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Angular JS -->  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<!--Route Guard -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>

<!-- Bootstrap CDN -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>


<!-- Controller.js -->
<script src="controller.js"></script>

<body ng-app="myApp">

<div ng-controller="datactrl">
    <ul>
        <h4>Name And Age Of The persons</h4>
        <li ng-repeat="person in persons">
            {{ person.Name+ ':' + person.Age }}          
        </li>           
    </ul>
</div>

</body>
</html>

controller.js:

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

app.controller('datactrl', function($scope, $http) {
    $http.get('http://127.0.0.1/AngularJS/HttpGet/database.json')
    .then(function(response) {
        $scope.persons = response.records;
    });
});

database.json:

{
    "records": [
    {
    "Name" : "asd",
    "Age" : "20"
    },

    {
    "Name" : "asd",
    "Age" : "20"
    },

    {
    "Name" : "asd",
    "Age" : "20"
    }

    ]
}

Can anybody please help me to resolve this issue..?

24
  • Give relative path for the database.json file instead of providing absolute path Commented May 5, 2018 at 12:57
  • I also tried giving the path as file:///D:/AngularJS/DemoJS/assets/database.json... but still the same error Commented May 5, 2018 at 12:57
  • Where is the database.json, it might be in your project folder so give the relative path from your controller file for that URL Commented May 5, 2018 at 12:58
  • oh sorry .... missed that path .. i will correct Commented May 5, 2018 at 12:59
  • You can also take a referece from here stackoverflow.com/a/33753986/7053190 Commented May 5, 2018 at 13:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.