Angular JSONP "Uncaught SyntaxError: Unexpected token :"

Angular JSONP "Uncaught SyntaxError: Unexpected token :"

我正在尝试在我的 angular 应用程序中向 http://catfacts-api.appspot.com/api/facts' 发出请求。我使用 $http 服务对页面进行了 http GET,但出现跨源错误:

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

但我收到跨源错误

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.

我尝试使用 JSONP,但出现语法错误。我很困惑为什么会这样。

$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 

您可以查看页面here

我认为你的 api 有误,你当前的 api 状态

{"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"}

尝试将其更改为

{"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"}

只需删除方括号,因为在 json 格式中,这个简单的结果应该是

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

如果你想在这个对象中嵌套另一个对象,你需要使用方括号,例如

 "Names" : [   
                            { "firstName" : "John",  
                              "lastName"  : "Doe",
                              "age"       : 23 },

                            { "firstName" : "Mary",  
                              "lastName"  : "Smith",
                              "age"       : 32 }
                          ],  "some_var" : "some_val"} 

如您所见,我们可以在 "Names" 中传递另一个对象,因为您只传递一个字符串,不需要使用方括号。

另一种解决方案可以是

{"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"}

它应该可以工作。

您可以通过以下任一方法解决此问题

1) 在您的 API 端点创建一个 Access-Control-Allow-Origin header。然后尝试一个简单的获取。因为错误是,

No 'Access-Control-Allow-Origin' header is present on the requested resource.

笨蛋:https://plnkr.co/edit/xFR0CEiZTioR2nEW4HEx

2) 如果您打算从 JSONP 请求中获取响应,您的请求应该像这样围绕回调。

JSON_CALLBACK({
  "facts": ["Cats purr at the same frequency as an idling diesel engine, about 26 cycles per second."],
  "success": "true"
 })

现在您 return 正在 JSON object。 笨蛋:https://plnkr.co/edit/M3c849O0PoAmxYbsk9tE

文档:https://docs.angularjs.org/api/ng/service/$http#jsonp

Update:此外,在执行 get 请求时,谨慎的做法是 return header、mimetype: application/json

更新 2:使用 `ngResource 也失败了。
笨蛋:https://plnkr.co/edit/wdoD73920Mnc8RRmoUKX?p=preview