3

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!

1
  • Do you get any different result if you remove the "responseType" setting? Commented Jan 9, 2015 at 20:03

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried them, none of them working. the error is something like: SyntaxError: Unexpected token {
another error is: SyntaxError: Unexpected token '
I'm also having SyntaxError: Unexpected token i if I use your JSON. Try some some simple json e.g. [{ "foo": "bar" }], restart node (or other server), clear caches, and everything should work fine.
0

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

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

Comments

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.