Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS intercept all $http requests

Tags:

angularjs

I can't seem to get the $httpProvider.interceptors to actually intercept. I created a sample on JSFiddle that logs when the interceptor is run and when the $http response is successful. The request interceptor is run after the response is already returned as successful. This seems a bit backwards.

I can't use transformRequest because I need to alter the params in the config. That part isn't shown in the sample.

I'm using AngularJS 1.1.5

http://jsfiddle.net/skeemer/K7DCN/1/

Javascript

var myApp = angular.module('myApp', []);

myApp.factory('httpInterceptor', function ($q) {
    return {
        request: function (config) {
            logIt('- Modify request');
            return config || $q.when(config);
        }
    };
});

myApp.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
});

function MyCtrl($scope, $http) {
    // Hit a server that allows cross domain XHR
    $http.get('http://server.cors-api.appspot.com/server?id=8057313&enable=true&status=200&credentials=false')
    .success(function (data) {
        //logIt(data[0].request.url);
        logIt('- GET Successful');
    });

    $scope.name = 'Superhero';
}


// Just the logging
var logs = document.getElementById('logs');

function logIt(msg) {
    var e = document.createElement('div');
    e.innerHTML = msg;
    logs.insertBefore(e, logs.firstChild);
}

HTML

<div ng-controller="MyCtrl">Hello, {{name}}!</div>
<br/>
<div id="logs"></div>
like image 540
skeemer Avatar asked Jun 08 '13 01:06

skeemer


People also ask

How do you modify the $HTTP request default Behaviour?

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g. $httpProvider. defaults.

What is interceptor in AngularJS?

This interceptor is called when the $http receives the response from the server. This function receives a response object as a parameter return a response object or a promise. A response interceptor is used to modify the response data or adding a new set of values, calling another module or services call.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

Is http request is synchronous or asynchronous in AngularJS?

The problem is as follows, $http. get is asynchronous, before the response is fetched, the function returns. Therefore the calling function gets the data as empty string.


2 Answers

If you want the option to accept/reject a request at interception time you should be using $httpProvider.responseInterceptors, see example below:

$httpProvider.responseInterceptors.push(function($q) {
    return function(promise){
        var deferred = $q.defer();
        promise.then(
            function(response){ deferred.reject("I suddenly decided I didn't like that response"); },
            function(error){ deferred.reject(error); }
        );
        return deferred.promise;
    };
});

EDIT Didn't read your comment, indeed responseInterceptors is now obsolete an that's how you do it instead:

$httpProvider.interceptors.push(function($q) {
    return {
        request: function(config){ return config; },
        response: function(response) { return $q.reject(response); }
    };
});

I learned something useful, thanks

like image 126
Renaud Avatar answered Sep 17 '22 07:09

Renaud


The request interceptor isn't running after the data is returned. It's running before. Your logIt function inserts the newest message at the top. If you change your code to use the $log service, you'll see that the interceptor runs first.

like image 38
Mike Pugh Avatar answered Sep 17 '22 07:09

Mike Pugh