这篇文章主要介绍了Angular.js中$http拦截器有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
罗甸网站建设公司成都创新互联,罗甸网站设计制作,有大型网站制作公司丰富经验。已为罗甸1000多家提供企业网站建设服务。企业网站搭建\外贸网站建设要多少钱,请找那个售后服务好的罗甸做网站的公司定做!
前言
$http service在Angular中用于简化与后台的交互过程,其本质上使用XMLHttpRequest或JSONP进行与后台的数据交互。在与后台的交互过程中,可能会对每条请求发送到Server之前进行预处理(如加入token),或者是在Server返回数据到达客户端还未被处理之前进行预处理(如将非JSON格式数据进行转换);当然还有可能对在请求和响应过程过发生的问题进行捕获处理。所有这些需求在开发中都非常常见,所以Angular为我们提供了$http拦截器,用来实现上述需求。
什么是拦截器
顾名思义,拦截器就是在目标达到目的地之前对其进行处理以便处理结果更加符合我们的预期。Angular的$http拦截器是通过$httpProvider.interceptors数组定义的一组拦截器,每个拦截器都是实现了某些特定方法的Factory:

实现拦截器
http拦截器一般通过定义factory的方式实现:
myApp.factory('MyInterceptor', function($q) {
return {
// 可选,拦截成功的请求
request: function(config) {
// 进行预处理
// ...
return config || $q.when(config);
},
// 可选,拦截失败的请求
requestError: function(rejection) {
// 对失败的请求进行处理
// ...
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// 可选,拦截成功的响应
response: function(response) {
// 进行预处理
// ....
return response || $q.when(reponse);
},
// 可选,拦截失败的响应
responseError: function(rejection) {
// 对失败的响应进行处理
// ...
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
}
};
});随后,我们需要将实现的拦截器加入到$httpProvider.interceptors数组中,此操作一般在config方法中进行:
myApp.config(function($httpProvider) {
$httpProvider.interceptors.push(MyInterceptor);
});当然,我们也可以通过匿名factroy的方式实现:
$httpProvider.interceptors.push(function($q) {
return {
request: function(config) {
// bala
},
response: function(response) {
// bala
},
// bala
};
});可以看到,每个拦截器都可以实现4个可选的处理函数,分别对应请求(成功/失败)和响应(成功/失败)的拦截:
1、request:此函数在$http向Server发送请求之前被调用,在此函数中可以对成功的http请求进行处理,其包含一个http config对象作为参数,这里对config对象具有完全的处理权限,甚至可以重新构造,然后直接返回此对象或返回包含此对象的promise即可。如果返回有误,会造成$http请求失败。如开发中经常需要在请求头中加入token以便验证身份,我们可以作如下处理:
request: function(config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers['X-Access-Token'] = $window.sessionStorage.token;
}
return config || $q.when(config);
}2、requestError:此方法会在前一个拦截器抛出异常或进行了reject操作时被调用,在这里可以进行恢复请求的操作,或者进行一些对于请求时发起动作的处理(如取消loading等);
3、response:此函数在$http从Server接收到响应时被调用,在此函数中可以对成功的http响应进行处理,这里具有对响应的完全处理权限,甚至可以重新构造,然后直接返回响应或返回包含响应的promise即可。如果返回有误,会造成$http接收响应失败;
4、responseError:此方法会在前一个拦截器抛出异常或进行了reject操作时被调用,在这里可以进行恢复响应的操作,进行一些针对错误的处理。
使用用例
为演示Angular $http拦截器的使用方法,下面通过几个常用的用例来说明:
利用request拦截器模拟实现Angular的XSRF(即CSRF)防御
CSRF,即“跨站请求伪造”,不过不知道为什么Angular将其称为XSRF。当处理与后台交互时,Angular的$http会尝试从客户端cookie中读取一个token,其默认的key为XSRF-TOKEN,并构造一个名为X-XSRF-TOKEN的http头部,与http请求一起发送到后台。Server端就可以根据此token识别出请求来源于同域,当然跨域的请求$http不会加入X-XSRF-TOKEN头部。那我们可以利用request拦截器通过如下方式在同域请求头部中加入此头部以达到模拟Angular的XSRF(即CSRF)防御机制的实现效果:
/**
* 正式开发中Angular会主动进行XSRF防御(只要cookie中存在key为`XSRF-TOKEN`的token),
* 一般不需要手动进行,除非cookie中不存在key为`XSRF-TOKEN`的token,这里只是模拟实现
*/
request: function(config) {
if(config.url.indexOf('SAME_DOMAIN_API_URL') > -1) {
config.headers['X-XSRF-TOKEN'] = $cookies.get('XSRF-TOKEN');
}
return config;
}如果初始http请求头部类似于:
"headers": {
"Accept": "application/json, text/plain, */*"
}那么经过上述的拦截器后,其http请求头部就变成了:
"headers": {
"Accept": "application/json, text/plain, */*",
"X-XSRF-TOKEN": X-XSRF-TOKEN-VALUE
}利用response拦截器模拟实现Angular JSON易损性(JSON vulnerability)防御
Angular在$http请求安全性方面不仅为我们设计了XSRF(CSRF)防御,而且针对请求JSON数据的Url可能通过类似于
基本
文件
流程
错误
SQL
调试
- 请求信息 : 2026-05-19 19:09:49 HTTP/1.1 GET : /article/pechec.html
- 运行时间 : 2.3835s ( Load:0.0063s Init:1.6943s Exec:0.6739s Template:0.0091s )
- 吞吐率 : 0.42req/s
- 内存开销 : 2,243.70 kb
- 查询信息 : 12 queries 5 writes
- 文件加载 : 36
- 缓存信息 : 0 gets 0 writes
- 配置加载 : 130
- 会话信息 : SESSION_ID=1kabtko3to0838aa97n1t5jqc3
- /www/wwwroot/tsicrk.com/index.php ( 1.09 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/ThinkPHP.php ( 4.61 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Think.class.php ( 12.26 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Storage.class.php ( 1.37 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Storage/Driver/File.class.php ( 3.52 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Mode/common.php ( 2.82 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Common/functions.php ( 53.56 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Hook.class.php ( 4.01 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/App.class.php ( 13.49 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Dispatcher.class.php ( 14.79 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Route.class.php ( 13.36 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Controller.class.php ( 11.23 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/View.class.php ( 7.59 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/BuildLiteBehavior.class.php ( 3.68 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ParseTemplateBehavior.class.php ( 3.88 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ContentReplaceBehavior.class.php ( 1.91 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Conf/convention.php ( 11.15 KB )
- /www/wwwroot/tsicrk.com/App/Common/Conf/config.php ( 2.14 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Lang/zh-cn.php ( 2.55 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Conf/debug.php ( 1.49 KB )
- /www/wwwroot/tsicrk.com/App/Home/Conf/config.php ( 0.31 KB )
- /www/wwwroot/tsicrk.com/App/Home/Common/function.php ( 3.33 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ReadHtmlCacheBehavior.class.php ( 5.62 KB )
- /www/wwwroot/tsicrk.com/App/Home/Controller/ArticleController.class.php ( 6.02 KB )
- /www/wwwroot/tsicrk.com/App/Home/Controller/CommController.class.php ( 1.60 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Model.class.php ( 60.11 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php ( 32.43 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db/Driver/Pdo.class.php ( 16.74 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Cache.class.php ( 3.83 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Cache/Driver/File.class.php ( 5.87 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template.class.php ( 28.16 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template/TagLib/Cx.class.php ( 22.40 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template/TagLib.class.php ( 9.16 KB )
- /www/wwwroot/tsicrk.com/App/Runtime/Cache/Home/7540f392f42b28b481b30614275e4e55.php ( 17.71 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/WriteHtmlCacheBehavior.class.php ( 0.97 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ShowPageTraceBehavior.class.php ( 5.24 KB )
- [ app_init ] --START--
- Run Behavior\BuildLiteBehavior [ RunTime:0.000005s ]
- [ app_init ] --END-- [ RunTime:0.000028s ]
- [ app_begin ] --START--
- Run Behavior\ReadHtmlCacheBehavior [ RunTime:0.000269s ]
- [ app_begin ] --END-- [ RunTime:0.000287s ]
- [ view_parse ] --START--
- [ template_filter ] --START--
- Run Behavior\ContentReplaceBehavior [ RunTime:0.000070s ]
- [ template_filter ] --END-- [ RunTime:0.000102s ]
- Run Behavior\ParseTemplateBehavior [ RunTime:0.006239s ]
- [ view_parse ] --END-- [ RunTime:0.006265s ]
- [ view_filter ] --START--
- Run Behavior\WriteHtmlCacheBehavior [ RunTime:0.000160s ]
- [ view_filter ] --END-- [ RunTime:0.000177s ]
- [ app_end ] --START--
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') LIMIT 1' at line 1
[ SQL语句 ] : SELECT `id`,`pid`,`navname` FROM `cx_nav` WHERE ( id= ) LIMIT 1
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') LIMIT 1' at line 1
[ SQL语句 ] : SELECT `id`,`navname` FROM `cx_nav` WHERE ( id= ) LIMIT 1
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
[ SQL语句 ] : SELECT `id`,`navname` FROM `cx_nav` WHERE ( pid= )
- [8] Undefined index: pid /www/wwwroot/tsicrk.com/App/Home/Controller/ArticleController.class.php 第 47 行.
- [8] Undefined index: db_host /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 120 行.
- [8] Undefined index: db_port /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 121 行.
- [8] Undefined index: db_name /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 122 行.

2.3835s
