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?
My experiments showed that in case of requests for templates, the config
object has a cache
property, and a call to config.cache.info()
will return an object:
{id: "templates", size: 7}
This is probably the only reliable way to do it without inspecting the URL.
I also tried inspecting stack traces, but with no success - hard to find any reasonable pattern, and it certainly shouldn't be relied upon.
Still in my opinion the best way is to check the URL.
A quick bit of inspection led me to hypothesize that template requests are made with an Accept header of text/html which lets you get round them quickly. Lots of plugins don't seem to obey that for loading templates but a few indexOf's on the url may clean that up for you. My example:
$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;
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With