2015-08-20 52 views
0

我想从我的角度应用程序从远程Web服务获取数据。由于服务器使用WSO2 API管理器处理请求,因此需要将“授权:承载31363a37a017a4b2e9b1104981ff”与请求一起传递。角度远程服务器Web服务授权

我的要求看起来如下

movieControllers.controller('MovieListCtrl', ['$scope', '$http', 
 
    function($scope, $http) { 
 
    $http.jsonp('http:myserverurl/1.0.0' 
 
     ,{ 
 
    headers: {Authorization: 'Bearer AUTH_CODE_HERE'} 
 
    }).success(function(data, status, headers, config) { 
 
     $scope.movies= data; 
 
     $scope.status = status; 
 
    
 
    }).error(function(error, status, headers, config) { 
 
     $scope.status = status; 
 
     
 
}); 
 

 
    }]);

但它给我 “未经授权的访问”。看来标题设置不正确。 然后我直接请求我的api。它不需要任何授权。它工作正常。

我是新来的角和这个API和Web服务的东西。我是否需要为Oauth安装额外的模块? (我猜这个授权是oauth。如果我错了,请纠正我)。任何人都可以指向正确的方向,并且非常感谢。 谢谢。

+0

您可以确保标题设置或不在标题请求中。我会建议你为类型的东西创建一个Interceptor。让我们知道您是否能够在Chrome中查看请求头。 –

+0

没有标题设置不正确。请求中无法看到标题。 – amilaishere

回答

0

之前$http.jsonp如果您分配授权。它会工作

$http.defaults.headers.common. Authorization = 'Bearer AUTH_CODE_HERE' 

在这种情况下,你的代码应该是 -

movieControllers.controller('MovieListCtrl', ['$scope', '$http', 
    function($scope, $http) { 

    $http.defaults.headers.common. Authorization = 'Bearer AUTH_CODE_HERE'; 

    $http.jsonp('http:myserverurl/1.0.0') 
    .success(function(data, status, headers, config) { 
    $scope.movies= data; 
    $scope.status = status; 

    }).error(function(error, status, headers, config) { 
    $scope.status = status; 

    }); 
}]); 
0

我还建议创建拦截器,拦截器,因为充当要求建设者在这里。

所有你需要做的是在$ httpProvider提拦截

var myApp = angular.module('myApp'); 
//Set configs 
myApp.config(function($httpProvider){ 
    //Add dependencyof interceptor 
    $httpProvider.interceptors.push('myInterceptor'); 
}); 

现在,在工厂建立一个拦截器

//Create you interceptor here 
mayApp.factory('myInterceptor', function() { 
     return { 
      request: function(config) {    
      config.headers[ 'Authorization' ] = 'Bearer AUTH_CODE_HERE'; 
      return config; 
      } 
     } 
    }); 

这样,你解决每个请求添加授权头。如果您想更改配置或想要为每个请求动态生成授权标头,则此拦截器也很有用。希望这对你有帮助。干杯!