Search code examples
angularjshttpjsonp

Angular JSONP "Uncaught SyntaxError: Unexpected token :"


I am trying to make a request to http://catfacts-api.appspot.com/api/facts' in my angular application. I used the $http service to make an http GET to the page, but I get a cross origin error:

$http({
    method: 'GET',
    url: 'http://catfacts-api.appspot.com/api/facts'
}).then(function(response) {
    console.log(response);
});

but I get a cross origin error

XMLHttpRequest cannot load http://catfacts-api.appspot.com/api/facts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://cat-facts-alexwohlbruck.c9users.io' is therefore not allowed access.

I tried to use JSONP, but I get a syntax error. I'm very confused as to why this is happening.

$http.jsonp('http://catfacts-api.appspot.com/api/facts?number=1&callback=JSON_CALLBACK').success(function(data) {
    console.log(data);
})

.

Uncaught SyntaxError: Unexpected token :          facts?number=1&callback=angular.callbacks._0:1 

You can view the page here


Solution

  • I think there is an error in your api, your current api states

    {"facts": ["In the wild, lions live for an average of 12 years and up to 16 years. They live up to 25 years in captivity."], "success": "true"}

    try changing it to

    {"facts": "In the wild, lions live for an average of 12 years and up to 16 years. They live up to 25 years in captivity.", "success": "true"}

    Just remove the square brackets, because in json format for this simple result should be

    {"variable_name" : "value" , "variable_name" : "value"}

    If you want to nest another object inside this one you need to use the square brackets for eg

     "Names" : [   
                                { "firstName" : "John",  
                                  "lastName"  : "Doe",
                                  "age"       : 23 },
    
                                { "firstName" : "Mary",  
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ],  "some_var" : "some_val"} 
    

    As you can see, we can pass another object in "Names", as you are only passing a string you don't need to use the square brackets.

    Another solution can be

    {"facts": [ "newFact" : "In the wild, lions live for an average of 12 years and up to 16 years. They live up to 25 years in captivity."], "success": "true"}

    and it should work.