为每个$ http呼叫生成标头的唯一值

时间:2015-05-13 20:28:15

标签: javascript angularjs http-headers

我有一个相当大的AngularJS应用程序,并且出于日志记录的目的,我的任务是为应用程序的所有HTTP请求添加一个自定义标头,其中包含每个请求的唯一ID。这对我们的API调用来说真的更有价值,但到目前为止我只是针对所有请求(获取模板,样式等)

我目前正在使用提供程序装饰器来修补$HttpProvider公开的每个方法(基于this post的实现),以便每次$http中的一个尝试调用ID方法}方法运行,并添加适当的标题:

module.config([
  '$provide',
  function ($provide) {
    $provide.decorator('$http', [
      '$delegate',
      function addUniqueIdHeader($http) {
        var httpMethods = ['get', 'post', 'put', 'patch', 'delete'];

        /**
         * Patched HTTP factory function that adds a request ID each time it is called.
         * @param  {string} method - A valid HTTP method.
         * @return {function} A function that sets various request properties.
         */
        function httpWithHeader(method) {
          return function(url, data, config) {
            config = config || {};
            config.headers = config.headers || {};

            // the magic
            config.headers['My-Custom-Header'] = aUniqueId();

            data = data || {};

            config.method = method.toUpperCase();

            // return `$http` with a modified config, adding the URL and data passed in
            // `_.extend()` is lodash, not underscore.
            return $http(_.extend(config, {
              url: url,
              data: data
            }));
          }
        };

        // back up the orginal methods and patch
        _.each(httpMethods, function (httpMethod) {
          var backupMethod = '_' + httpMethod;

          $http[backupMethod] = $http[httpMethod];
          $http[httpMethod] = httpWithHeader(httpMethod);
        });

        return $http;
      }
    ]);
  }
]);

到目前为止我的工作在某些时候有效,但似乎并不一致(有些API请求有,有些不要)。我应该注意到我们使用的是一个相当旧版本的AngularJS(1.0.6)而不是,我无法升级(尽可能多的我喜欢)因此无法使用请求拦截器。此外,我们在大多数API交互中使用Restangular。

我的问题是,是否正确使用提供者装饰器?如果是这样,是否有更简洁的方法来添加标题而不必覆盖/修补我忽略的每个单独的HTTP方法?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我最终通过使用Restangular的request interceptors来解决我的问题,因为我们使用的Angular版本没有将它们烘焙。