2

i am new in developing a website using angularJS as my client-side and i am trying to access my JSON thru API call with $http.get method for angular.

my issue is that my API call requires an Access Token. i always get this error whenever i try to refresh my page.

XMLHttpRequest cannot load http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.

i am currently using this code to fetch my data.

myApp.controller('loginCtrl', function($scope, $http) {
  $http.get("http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores")
    .then(function(response) {
      $scope.names = response.data.records;
    });
});

how do i insert an access token on the $http.get method.

2 Answers2

5

It depends on how your API get this access token. The most popular option is to just add specyfic header to your request

var req = {
   method: 'POST',
   url: 'http://example.com',
   headers: {
      'Authorization': 'access token'
   },
}

$http(req).then(function(){...}, function(){...});

you can also add it globally

module.run(function($http) {
  $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});

or by using Angular interceptors http://www.diwebsity.com/2015/12/17/interceptor-in-angular/

suvroc
  • 3,058
  • 1
  • 15
  • 29
1

You are running into a SOP issue that is described here https://en.wikipedia.org/wiki/Same-origin_policy

You should have a look here:

  1. Ways to circumvent the same-origin policy
  2. Same origin policy
  3. XMLHttpRequest Same Origin Policy
Community
  • 1
  • 1
Hitmands
  • 13,491
  • 4
  • 34
  • 69