Angular,$ http到api(跨域)

时间:2015-01-20 23:45:42

标签: angularjs http

我正试图在我的本地机器上使用api。我目前在我的本地主机上运行了一个grunt服务器:9000用于我的开发环境,我正在尝试调用seismi的api,以便有趣地玩一些像这样的数据:

$http.get('http://www.seismi.org/api/eqs/2011/03?min_magnitude=6').
  success(function(data, status, headers, config) {
    $scope.seismiData = data;
    console.log($scope.seismiData);
  }).
  error(function(data, status, headers, config) {
    console.log("error with initial fetch");    
  });

这只是使用页面上的示例 - http://www.seismi.org/api/。当我这样做时,我的控制台正在给我这个。

 XMLHttpRequest cannot load http://www.seismi.org/api/eqs/2011/03?min_magnitude=6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

我还是很陌生,所以我不知道如何解决这个问题,所以我可以使用api返回的json。如果有人能指出我正确的方向,我会非常感激。谢谢!

2 个答案:

答案 0 :(得分:2)

这是CORS / CSRF问题。请对这两个进行一些研究,有很多非常好的Stackoverflow答案解释了为什么会出现这个错误。

如果您只是在使用seismi的api并且只需要读取数据,那么您将能够使用$ http.jsonp而不是$ http.get。

答案 1 :(得分:2)

还有一种简单的方法可以启用CROS问题。

如果你正在使用chrome,你只想在localhost环境中测试一些东西。使用此Chrome扩展程序(Allow-Control-Allow-Origin: *)。安装是和CROS原产地一样。

此方法可让您按原样保留代码,并且仍然可以使用app API

希望这有帮助,
干杯!