8

With AngularJS interceptors, is it possible to differentiate my app calls to $http (direct either through $resource) from requests made by Angular itself for static resources, like views, without checking URLs?

I'm adding custom authorization header in HTTP interceptor like this:

transparentAuthServices.factory('authHttpInterceptor',
  function (localSessionStorage) {
    return {
      'request': function (config) {
        if (!config.ignoreAuthInterceptor && localSessionStorage.hasSession()) {
          var sessionId = localSessionStorage.getSession().sessionId;
          config.headers['Authorization'] = 'ARTAuth sessionId="' + sessionId + '"';
          return config;
        } else {
          return config;
        }
      }
    }
  };
});

It works fine but I don't need authorization for static resources and my server doesn't check them. I could check URLs and skip on those starting with '/app' (in my case) but I wonder is there an elegant solution?

4

2 回答 2

8

我的实验表明,在请求模板的情况下,该config对象具有一个cache属性,并且调用config.cache.info()将返回一个对象:

{id: "templates", size: 7}

这可能是不检查 URL 的唯一可靠方法。

我还尝试检查堆栈跟踪,但没有成功 - 很难找到任何合理的模式,当然不应该依赖它。

我仍然认为最好的方法是检查 URL。

于 2013-11-16T22:44:33.817 回答
1

快速的检查使我假设模板请求是使用 text/html 的 Accept 标头发出的,这使您可以快速绕过它们。许多插件似乎不遵守加载模板的要求,但 url 上的一些 indexOf 可能会为您清理。我的例子:

$httpProvider.interceptors.push(function () {
            return {
                request: function(config) {
                    if (config.url.indexOf('http') != 0
                        && config.headers.Accept !== 'text/html' /* Excludes template requests */
                        && config.url.indexOf('html') === -1 /* some plugins do requests with html */
                        && config.url.indexOf('tpl') === -1 /* match any template naming standards */) {
                        if (config.url.indexOf('/') == 0) {
                            config.url = apiEndpoint + config.url;
                        } else {
                            config.url = apiEndpoint + '/' + config.url;
                        }
                    }

                    return config;
                }
            }
        });

于 2015-11-10T08:58:57.517 回答