0

error :

Access to XMLHttpRequest at 'http://localhost:8080/api/v1/locations' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I test the get method in a request.http file of WebStorm and in Postman and that work , but that doesn't work in my Angularjs project . (I get from a Spring boot java project).

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);
    });
  });

my get function return something like this in postman

[
 {
   "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
}
]

the console : https://i.top4top.io/p_1507d02621.jpg

enter image description here

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Anass Tahiri
  • 45
  • 2
  • 7

2 Answers2

1

Postman usually doesn't use or consider the CORS header. The browser on the other hand needs it and if its missing, you get this error. In your backend code, you should whitelist the domain which you use to request the data. In your case this would be http://localhost:8080. I hope this makes sense.

Atanas Atanasov
  • 506
  • 7
  • 11
  • yes this is working thank you ,I add " @CrossOrigin(origins = "http://localhost:8000", maxAge = 3600)" in my case to my Java Spring boot controller . – Anass Tahiri Feb 16 '20 at 12:37
0

Add a .catch block to log errors:

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);
    });
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95