Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http interceptors for external urls

Tags:

angularjs

I have written an http interceptor to add authentication tokens to every request. In my html when i click a link this interceptor is not called. Not sure why that is happening?

My interceptor code -

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 -

<a data-ng-href="http://example.com/view"></a>
like image 269
Eshwari Chandrashekhar Avatar asked Feb 12 '15 11:02

Eshwari Chandrashekhar


People also ask

What are HTTP interceptors used for?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response.

When implementing an HTTP interceptor which method must be provided?

To implement an interceptor, you'll want to create a class that's injectable and that implements HttpInterceptor. The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent. req is the request object itself and is of type HTTP Request.

Can angular have multiple HTTP interceptors?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.


1 Answers

Your anchor tag will not actually make an ajax call, an http interceptors are for intercepting ajax calls made via angular. Clicking on that anchor tag will be like opening an URL in the browser.

In order to do the ajax call: you need to tweak the code in the following way:

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 like something:

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

And your HTML code will be:

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

The only thing is that, the external url you are making ajax call is either be on the same domain or must support cross origin request.

Hope this helps!

like image 61
Shashank Agrawal Avatar answered Nov 15 '22 05:11

Shashank Agrawal