很抱歉重复此问题的问题,但我真的试图寻求解决方案,但我找不到它。所以我使用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工作正常吗?
感谢您的回复。
答案 0 :(得分:2)
使用$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" ); });