Search code examples
angularjsjsonhttpget

$http.get 404 of JSON file using .then


I was running through a set of Angular videos on YouTube and found out that .success is deprecated, and to use .then instead. I get a 404 error using both a .json file and a .txt file. I tried using .txt as people mentioned browsers don't allow local files to access other local files.

This is the $http request I have at the moment

$http.get('data/ninjas.txt').then(function(response) {
       // Success!!!
        $scope.ninjas = response.data;
    });

This is my .json file which is valid through JSONLint

[{
    "name": "Yoshi",
    "belt": "green",
    "rate": 50,
    "available": true,
    "thumb": "content/img/yoshi.png"
}, {
    "name": "Crystal",
    "belt": "yellow",
    "rate": 30,
    "available": true,
    "thumb": "content/img/crystal.png"
}, {
    "name": "Ryu",
    "belt": "orange",
    "rate": 10,
    "available": true,
    "thumb": "content/img/ryu.png"
}, {
    "name": "Shaun",
    "belt": "black",
    "rate": 1000,
    "available": true,
    "thumb": "content/img/shaun.png"
}]

I tried testing using both httpster and using Brackets built in live preview. I get a 404 error, but the file does for sure exist as you can see in the image

enter image description here

If it helps, this is my whole app.js file

var myNinjaApp = angular.module('myNinjaApp', ['ngRoute']);

myNinjaApp.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/home', {
        templateUrl: 'views/home.html'
    })
        .when('/directory', {
        templateUrl: 'views/directory.html',
        controller: 'NinjaController'
    })
        .otherwise({
        redirectTo: '/home'
    });
}]);

myNinjaApp.controller('NinjaController', ['$scope', '$http', function($scope, $http){

    $scope.removeNinja = function(ninja){
        var removedNinja = $scope.ninjas.indexOf(ninja);
        $scope.ninjas.splice(removedNinja, 1)
    };

    $scope.addNinja = function(){
        $scope.ninjas.push({
            name: $scope.newninja.name,
            belt: $scope.newninja.belt,
            rate: parseInt($scope.newninja.rate),
            available: true
        }); 

        $scope.newninja.name = "";
        $scope.newninja.belt = "";
        $scope.newninja.rate = "";
    };

    $http.get('data/ninjas.txt').then(function(response) {
       // Success!!!
        $scope.ninjas = response.data;
    });

}]); 

Solution

  • To make the answer complete,

    Your root of your application is 'index.html', and because Angular is running within 'index.html', all files you load in your files are relative to your 'index.html'.

    An example of that is seen in your route configuration, where your templates are loaded starting at 'views/*', which is a child folder of your 'index.html'