Angular JS uses $ http () to get response with 200 status, but data is null

I am using this angular code:

$http({
  method: 'get',
  url: 'json/test.json',
  responseType: "json"
}).success(function(data, status, headers, config) {
  console.log('Success: ' + data);
  $scope.tests = data;
}).error(function(data, status, headers, config) {
  console.log('Error: ' + data);
});

      

the answer is:

[{
  id: 1,
  name: 'aaaa',
  age: 20
}, {
  id: 2,
  name: 'bbbbb',
  age: 21
}]

      

In the console, it prints:

Success: null

      

how it returns success, but the data is null.

any help is appreciated!

+3


source to share


2 answers


This can happen because it is json

not formatted properly. Try:

[
    {
        "id": 1,
        "name": "aaaa",
        "age": 20
    },
    {
        "id": 2,
        "name": "bbbbb",
        "age": 21
    }
]

      

and use

$http.get("json/test.json").success(function (data) {
    console.log('success: ' + data)
});

      



or you can use your original code but without responseType

, as @DeborahK found out:

$http({
  method: 'get',
  url: 'json/test.json'
}).success(function(data, status, headers, config) {
  console.log('Success: ' + data);
})

      

But you will need to format correctly json

anyway, otherwise angular will throw a parse exception.

+2


source


I don't know which version of AngularJS you are using, but assuming v1.6, try this:



$http.get("json/test.json").then(function(response) {
    console.log('success: ' + response.data);
}).catch(function(response) {
    console.log('error: ' + response.data);
});

      

0


source







All Articles