首页 > 代码库 > [AngularJS] Using AngularJS interceptors with $http

[AngularJS] Using AngularJS interceptors with $http

Sometimes you might need to modify HTTP requests and responses. This could be for a variety of reasons such as adding global logic handling for HTTP errors. With interceptors, you can easily accomplish this in your Angular applications.

var interceptor = function ($q, $location) {    return {        request: function (config) {            console.log(config);            return config;        },        response: function (result) {            console.log(‘Repos:‘);            result.data.splice(0, 10).forEach(function (repo) {                console.log(repo.name);            })            return result;        },        responseError: function (rejection) {            console.log(‘Failed with‘, rejection.status, ‘status‘);            if (rejection.status == 403) {                $location.url(‘/login‘);            }            return $q.reject(rejection);        }    }};angular.module(‘app‘, [])    .config(function ($httpProvider) {        $httpProvider.interceptors.push(interceptor);    })    .run(function ($http) {        $http.get(‘https://api.github.com/users/bclinkinbeard/reposefw‘);    });

 

In a lot of cases, interceptor can be used for Auth.

 

[AngularJS] Using AngularJS interceptors with $http