3

I'm trying to use an interceptor to add an 'Authorization' header to all my GET/POST requests. Here is the interceptor:

myApp.factory('httpRequestInterceptor', ['$rootScope', function ($rootScope) {
  return {
    request: function ($config) {
        $config.headers['Authorization'] = 'Basic ' + $rootScope.apiKey;
        return $config;
    }
  };
}]);

The interceptor is being used in the main module as follows in the myApp.config part:

$httpProvider.interceptors.push('httpRequestInterceptor');

For some reason I can't see the Authorization header in the network tab(I'm using Chrome) and it's not getting to the server and I don't get any errors. The GET/POST request in my application are to a remote server that is NOT in my domain.

Any idea what am I doing wrong here?

Solution: I found the problem, it was on the server side - apparently if I set the Access-Control-Allow-Headers in the response to * it doesn't work but if I specify the headers literally it works just fine.

4

4 回答 4

1

问题出在服务器端 - 显然在对 * 的响应中设置 Access-Control-Allow-Headers 不起作用,但按字面意思指定标题为我需要的(Access-Control-Allow-Headers: Authorization)工作得很好.

于 2015-07-01T11:16:09.633 回答
0

我认为您应该将其更改为

 myApp.factory('httpRequestInterceptor', ['$rootScope', function ($rootScope) {
    var injector = {
        request: function (config) {
               config.headers['Authorization'] = 'Basic ' + $rootScope.apiKey;
               return config;
        }
    };
   return injector;
    } ]);

试试这个网站

于 2015-07-01T05:29:33.710 回答
0

您可以使用:

myApp.run([
  '$http', '$rootScope',
  function($http, $rootScope) {
    $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.apiKey;
  }
]);
于 2015-07-01T06:39:32.020 回答
0

你总是可以告诉 angular 添加标题使用$httpProvider这样的:

myApp.config(['$httpProvider','$rootScope', function ($httpProvider, $rootScope) {
    $httpProvider.defaults.headers.common['Authorization'] = 'Basic' + $rootScope.apiKey;
}]);

这会将标头添加到所有请求。对于 get 和 post,您可以设置 : $httpProvider.defaults.headers.get['Authorization'] = '';$httpProvider.defaults.headers.post['Authorization'] = ''; 而不是$httpProvider.defaults.headers.common['Authorization'] 如果您不希望将标头添加到所有请求中。

于 2015-07-01T06:41:40.063 回答