Home Web Front-end JS Tutorial A brief analysis of AngularJs HTTP response interceptor_AngularJS

A brief analysis of AngularJs HTTP response interceptor_AngularJS

May 16, 2016 pm 03:23 PM
angularjs Interceptor

Why use interceptors?

Any time, if we want to add global functionality to the request, such as authentication, error handling, etc., it is a better way to intercept the request before it is sent to the server or when the server returns.

angularJs provides a way to process from the global level through interceptors.

Interceptor allows you to:

Intercept requests by implementing the request method: This method will be executed before $http sends the request to the background, so you can modify the configuration or do other operations. This method receives a request configuration object as a parameter and must return a configuration object or a promise. If an invalid configuration object or promise is returned, it will be rejected, causing the $http call to fail.

Intercept the response by implementing the response method: This method will be executed after $http receives the response from the background, so you can modify the response or do other operations. This method receives a response object as a parameter and must return a response object or promise. The response object includes request configuration, headers, status and data from the background. If an invalid response object is returned or the promise will be rejected, the $http call will fail.

Intercept request exceptions by implementing the requestError method: Sometimes a request fails to be sent or is rejected by the interceptor. The request exception interceptor captures requests that were interrupted by the previous request interceptor. It can be used to restore the request or sometimes to undo the configuration made before the request, such as closing the progress bar, activating buttons and input boxes, etc.

Intercept response exceptions by implementing the responseError method: Sometimes our background call fails. It's also possible that it was rejected by a request interceptor, or interrupted by a previous response interceptor. In this case, the response exception interceptor can help us resume the background call.

The core of the interceptor is the service factory, which is added to the $httpprovider.interceptors array. Register in $httpProvider.

AngularJs provides four interceptors, including two success interceptors (request, response) and two failure interceptors (requestError, responseError).

Add one or more interceptors to the service:

angular.module("myApp", []) 
  .factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) { 
    var httpInterceptor = { 
      'responseError' : function(response) { 
        ...... 
        return $q.reject(response); 
      }, 
      'response' : function(response) { 
        ...... 
        return response; 
      }, 
      'request' : function(config) { 
        ...... 
        return config; 
      }, 
      'requestError' : function(config){ 
        ...... 
        return $q.reject(config); 
      } 
    } 
  return httpInterceptor; 
} 
Copy after login

Then use $httpProvider to register the interceptor in the .config() function

angular.module("myApp", []) 
.config([ '$httpProvider', function($httpProvider) { 
  $httpProvider.interceptors.push('httpInterceptor'); 
} ]); 
Copy after login

Actual example: (Interception of 401, 404)

routerApp.config([ '$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push('httpInterceptor'); 
  } ]); 
  routerApp.factory('httpInterceptor', [ '$q', '$injector',function($q, $injector) { 
    var httpInterceptor = { 
      'responseError' : function(response) { 
        if (response.status == 401) { 
          var rootScope = $injector.get('$rootScope'); 
          var state = $injector.get('$rootScope').$state.current.name; 
          rootScope.stateBeforLogin = state; 
          rootScope.$state.go("login"); 
          return $q.reject(response); 
        } else if (response.status === 404) { 
          alert("404!"); 
          return $q.reject(response); 
        } 
      }, 
      'response' : function(response) { 
        return response; 
      } 
    } 
    return httpInterceptor; 
  }  
]); 
Copy after login

Session injection (request interceptor)

There are two ways to implement server-side authentication. The first is traditional Cookie-Based authentication. The user is authenticated for each request through server-side cookies. Another way is Token-Based verification. When the user logs in, he will get a sessionToken from the background. The sessionToken identifies each user on the server side and is included in every request sent to the server.

The following sessionInjector adds the x-session-token header to each captured request (if the current user is logged in):

<!-- lang: js -->
module.factory('sessionInjector', ['SessionService', function(SessionService) {
  var sessionInjector = {
    request: function(config) {
      if (!SessionService.isAnonymus) {
        config.headers['x-session-token'] = SessionService.token;
      }
      return config;
    }
  };
  return sessionInjector;
}]);
module.config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('sessionInjector');
}]);
Copy after login

Then create a request:

<!-- lang: js -->
$http.get('https://api.github.com/users/naorye/repos');
Copy after login

The configuration object before being intercepted by sessionInjector is like this:

<!-- lang: js -->
{
  "transformRequest": [
    null
  ],
  "transformResponse": [
    null
  ],
  "method": "GET",
  "url": "https://api.github.com/users/naorye/repos",
  "headers": {
    "Accept": "application/json, text/plain, */*"
  }
}
Copy after login

The configuration object after being intercepted by sessionInjector is like this:

<!-- lang: js -->
{
  "transformRequest": [
    null
  ],
  "transformResponse": [
    null
  ],
  "method": "GET",
  "url": "https://api.github.com/users/naorye/repos",
  "headers": {
    "Accept": "application/json, text/plain, */*",
    "x-session-token": 415954427904
  }
}
Copy after login

The above content introduces you to the relevant knowledge of AngularJs HTTP response interceptor. I hope that sharing this article can help you.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Demystifying the interceptor mechanism in Golang Demystifying the interceptor mechanism in Golang Apr 08, 2024 am 08:39 AM

Interceptor is a design pattern that allows custom behavior to be inserted before and after method execution. In Go, it can be implemented through net/http middleware. It has the advantages of scalability, reusability, testability, etc., and can be used in scenarios such as authentication, authorization, caching, logging, and custom error handling.

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Tips for using route interceptors in uniapp Tips for using route interceptors in uniapp Dec 17, 2023 pm 04:30 PM

Tips for using route interceptors in uniapp In uniapp development, route interceptors are a very common function. Route interceptors allow us to perform some specific operations before routing jumps, such as permission verification, page passing parameters, etc. In this article, we will introduce the tips for using route interceptors in uniapp and provide specific code examples. Create a route interceptor First, we need to create a route interceptor in the uniapp project. The creation method is as follows: Create an inter in the project root directory

Comprehensive analysis of interceptors in Golang Comprehensive analysis of interceptors in Golang Apr 07, 2024 am 10:18 AM

In Golang, interceptors can be used to insert additional code before and after function execution. The scenarios include logging, authentication, caching, etc. Interceptors are implemented by creating a handler function type and then creating the interceptor function that accepts the handler function and returns a new handler function that contains additional logic. In actual combat, we can use interceptors to record all requests to facilitate debugging and analysis.

Understand the principles and advantages of Spring interceptors Understand the principles and advantages of Spring interceptors Dec 30, 2023 pm 12:25 PM

Explore the working principle and advantages of Spring interceptor Introduction: The Spring framework is one of the most commonly used frameworks in Java development. It provides rich functions and flexibility, allowing developers to develop applications more efficiently. One of the important components is the interceptor. This article will delve into the working principles and advantages of Spring interceptors and give specific code examples. 1. How Spring interceptor works Spring interceptor uses aspect-oriented programming (

Mastering interceptors in Golang Mastering interceptors in Golang Apr 07, 2024 pm 09:33 PM

Interceptors allow custom logic to be inserted into Go applications without modifying existing code. They can be used for authentication, logging, error handling, performance monitoring, etc. Creating an interceptor requires implementing the Handler interface, which defines the ServeHTTP() method for processing HTTP requests and the Next() method for passing control. Practical examples show how to use logging interceptors to log the URL paths of all incoming requests, and how to chain multiple interceptors (such as authentication interceptors) together to create complex application logic.

Does golang have an interceptor? Does golang have an interceptor? Jul 18, 2023 pm 02:23 PM

Golang does not provide a built-in interceptor, but you can use language features such as functions, interfaces, and structures to achieve similar functions. The following are commonly used interceptor implementation methods: 1. Functional interceptor, by processing the request before it reaches the handler and its Then call the function to implement the interceptor; 2. Interface interceptor, implement the interceptor by defining an interface and implementing the interface before and after the target handler. This method can make the interceptor more flexible and can be used in different situations. Implement different interceptor logic on the interface.

See all articles