添加 header 到 angular $resource 请求

Adding header to angular $resource requests

我正在尝试向 angular(用于访问 REST 服务器的资源)发送的所有 http 请求添加 header,以添加基本身份验证信息(来自用户输入 username/password).

当用户点击登录按钮时,我认为这就像 $http.defaults.headers.common['Authorization'] = value;(其中值是格式正确的身份验证信息)一样简单,但是当发送请求时,403 Unauthorized 是 return ed,并检查 Chrome 的网络选项卡中的请求 header 未在简单的资源查询中设置。

我已经搜索了一段时间,有几个问题与此相关,表明 CORS 是问题所在(不是,我在服务器端设置了正确的 headers,并且还在 chrome 中尝试 运行 网络安全关闭只是为了仔细检查这没有干扰)。其他答案建议使用拦截器,但在我看来,对于这样一个简单的任务来说,这似乎非常 over-engineered(尽管如果这是唯一的方法,我想我将不得不使用它)。

编辑:附加信息:我确信 CORS 不是问题,因为对不需要身份验证的同一服务器的请求成功并且 return 预期的响应。这是授权 header 未正确设置(或根本未设置)的问题。

最佳做法是创建一个 Http 请求拦截器并在其中添加授权 header。

angular.module("MyApp").factory("authHttpRequestInterceptor", ["authenticationDataService",
   function (authenticationDataService) {

       return {

           request: function (config) {
               // This is the authentication service that I use.
               // I store the bearer token in the local storage and retrieve it when needed.
               // You can use your own implementation for this
               var authData = authenticationDataService.getAuthData();

               if (authData && authData.accessToken) {
                   config.headers["Authorization"] = 'Bearer'+ authData.accessToken;
               }

               return config;
   }
};
}]);

之后在主模块中注册拦截器:

angular.module("MyApp").config([
   "$httpProvider", function ($httpProvider) {
       $httpProvider.interceptors.push('authHttpRequestInterceptor');
   }]);

你可以使用$httpProvider.interceptors。如果你使用$resource,请尝试使用它的属性 transformRequest。也许它可以帮助你。