Http Interceptors for External URLs

I wrote an http interceptor to add authentication tokens for each request. In my html, when I click the link, this interceptor is not called. Not sure why this is happening?

My interceptor code is

angular.module('demo', []) .factory('httpAuthorizationInterceptor',['$window', function ($window) { return { request: function (config) { if (config.url.indexOf('login') == -1) { config.headers['Authorization'] = 'Session ' +<session_id>; } return config || $q.when(config); } }; }]) 

My html is

 <a data-ng-href="http://example.com/view"></a> 
+5
source share
1 answer

Your anchor tag won't actually make an ajax call, http interceptors are designed to intercept ajax calls made through angular. Clicking on this anchor tag will look like opening a URL in a browser.

To make an ajax call: you need to configure the code as follows:

 angular.module('demo', []) .config(['$httpProvider', function ($httpProvider) { var interceptor = [function() { return { 'request': function(config) { if (config.url.indexOf('login') == -1) { config.headers['Authorization'] = 'Session ' + <session_id>; } return config; } }; }]; $httpProvider.interceptors.push(interceptor); }]); 

And now your controller code will look something like:

 $scope.doSomething = function() { $http({method: 'GET', url: 'http://example.com/view'}).then(function(data) { // success }); }; 

And your HTML code will look like this:

 <a href="doSomething()"></a> 

The only thing is that the external url that you make the ajax call is either in the same domain or must support a cross-lookup request.

Hope this helps!

+3
source

Source: https://habr.com/ru/post/1213233/


All Articles