我正在学习Angular JS,并且遇到了HTTP Get Request的问题。这是我的代码:
function countryController($scope,$http) {
delete $http.defaults.headers.common['X-Requested-With'];
$http.get("http://localhost:8080/countrybook/api/v1/countrybook")
.success(function(response) {
$scope.countries = response;
})
.error(function(response){
alert(response);
});
}
我得到一个空白的错误响应(警告中没有任何内容。当我在firebug中调试时,由于某种原因我看到响应是“”)。
我的标题如下:
响应标题:
Cache-Control private, must-revalidate
Content-Length 355
Content-Type application/javascript
Date Sat, 15 Nov 2014 16:53:52 GMT
Last-Modified Sat, 15 Nov 2014 16:52:06 GMT
Server WebStorm 9.0.1
请求标题:
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cache-Control max-age=0
Connection keep-alive
Host localhost:63342
If-Modified-Since Sat, 15 Nov 2014 16:52:06 GMT
Referer http://localhost:63342/CountryBook/index.html
User-Agent Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
我在Firebug中看到的响应是:
function countryController($scope,$http) {
delete $http.defaults.headers.common['X-Requested-With'];
$http.get("http://localhost:8080/countrybook/api/v1/countrybook")
.success(function(response) {
$scope.countries = response;
})
.error(function(response){
alert(response);
});
}
你可以帮我弄清楚什么是错的?当我直接从浏览器使用上面提到的http get请求中的相同链接时,我看到了我期望的响应。谢谢你的帮助!
答案 0 :(得分:3)
问题是:
The Same Origin Policy disallows reading the remote resource at localhost:8080/countrybook/api/v1/countrybook. This can be fixed by moving the resource to the same domain or enabling CORS.
通过在服务器端响应添加这两个标头来解决它:
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
Smartbart24 - 查看控制台日志有帮助。谢谢你的帮助!
答案 1 :(得分:1)
所以不知道你的后端我的一般$ http模式是:
$http.get(requestEndpointString)
.success(function(data,status,headers,config){
if(status!=200){
/*unexpected response status ...*/
console.log('API error status: '+status);
}else{
/* Success ... */
}
})
.error(function(data, status, headers, config){
/* Handle errors */
});
也许它可以帮助您通过记录响应状态进行调试? 也试着拿出这条线:
delete $http.defaults.headers.common['X-Requested-With'];