Search code examples
angularjscorssame-origin-policy

AngularJs -- Access to XMLHttpRequest has been blocked by CORS policy


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


Solution

  • 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.