错误:
CORS策略已阻止从来源“ http://localhost:8080/api/v1/locations”访问“ http://localhost:8000”处的XMLHttpRequest:请求的资源上没有“ Access-Control-Allow-Origin”标头。
我在WebStorm的request.http文件和Postman中测试了get方法,该方法可以工作,但是在我的Angularjs项目中不起作用。 (我来自一个Spring Boot Java项目)。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://localhost:8080/api/v1/locations")
.then(function(response) {
$scope.result = response.data;
console.log("OK:", response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
});
我的get函数在邮递员中返回类似的内容
[
{
"datetime": "2019-01-10T19:00:00.000+0000",
"user": {
"firstName": "thr",
"lastName": "an",
"id": 1
},
"speed": 0.0,
"latitude": 37.421998333333335,
"longitude": -122.08400000000002,
"id": 1
},
{
"datetime": "2019-01-10T19:01:00.000+0000",
"user": {
"firstName": "thr",
"lastName": "an",
"id": 1
},
"speed": 1.575,
"latitude": 37.42198333333335,
"longitude": -122.080000000002,
"id": 2
}
]
答案 0 :(得分:1)
邮递员通常不使用或不考虑CORS标头。另一方面,浏览器需要它,如果缺少它,则会出现此错误。
在您的后端代码中,您应该将用于请求数据的域列入白名单。在您的情况下,该值为http://localhost:8080
。
我希望这是有道理的。
答案 1 :(得分:0)
添加一个.catch
块以记录错误:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://localhost:8080/api/v1/locations")
.then(function(response) {
$scope.result = response.data;
console.log("OK:", response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
});