Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

I'm 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 response is like this:

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

In the console, it prints:

Success: null

how come it returns success, but data is null.

any help appreciated!

like image 607
Peter Huang Avatar asked Jan 25 '26 00:01

Peter Huang


1 Answers

This might happen because json is 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 may use your original code but without responseType as @DeborahK figured out:

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

But anyway you would need to format your json properly, otherwise angular will raise parsing exception.

like image 114
sbedulin Avatar answered Jan 26 '26 18:01

sbedulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!