2015-12-21 54 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