Access Control Allow Origin问题和angular$http服务

Access-Control-Allow-Origin issue and angular $http service

本文关键字:angular http 服务 问题 Control Allow Origin Access      更新时间:2023-09-26

很抱歉为这个问题重复了一个问题,但我确实试图寻找解决方案,但找不到。所以我使用angular$http.get xhr请求从公共api中检索数据。我有下一个代码

 $http.get('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2000&sold_in_us=1')
     .success(function(d){ console.log(d); })
     .error(function(d){ console.log( "nope" ); 
 });

这在控制台中返回:

XMLHttpRequest cannot load http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'blah-my-localhost-blah' is therefore not allowed access. 

然而,如果我使用jquery getJson方法,它工作得很好:

$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", {cmd:"getMakes", year:"2009"},                      
  function(data) {
    console.log(data);
  });

很明显,我可以配置angular来发送正确的请求,因为jQuery工作得很好?

感谢您的回复。

使用$http.jsonp方法执行jsonp请求,并将JSON_CALLBACK作为回调名称:

$http.jsonp('http://www.carqueryapi.com/api/0.3/?callback=JSON_CALLBACK&cmd=getMakes&year=2000&sold_in_us=1')
     .success(function(d){ console.log(d); })
     .error(function(d){ console.log( "nope" ); });