2015-12-21 55 views
2

我是新開發一個使用angularJS作爲客戶端的網站,我試圖通過使用$ http.get方法爲角度訪問我的JSON。如何在angularjs中添加訪問令牌http

我的問題是我的API調用需要一個訪問令牌。每當我嘗試刷新頁面時,我總會遇到此錯誤。

XMLHttpRequest無法加載http://unexus-api-dev-3urcgetdum.elasticbeanstalk.com/drugstores。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許訪問原產地'http://localhost:8888'。

我目前使用該代碼來獲取我的數據。

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

如何插入在$ http.get方法的訪問令牌。

回答

3

這取決於您的API如何獲取此訪問令牌。最流行的選擇是僅specyfic頭添加到您的要求

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

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

你也可以將其添加在全球

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

或使用角攔截 http://www.diwebsity.com/2015/12/17/interceptor-in-angular/

+0

我仍然得到即使我做了所有你說同樣的錯誤。 –

+0

來解決這個錯誤遵循@Hitmands指令 – suvroc