-
2022-03-08 14:15:09
拦截器(interceptor)是那些有助于阻止或改变请求或响应的拦截器。协议拦截器通常作用于特定标头或一组相关标头。HttpClient库为拦截器提供支持。
HttpClient
请求拦截器
HttpRequestInterceptor
接口表示请求拦截器。此接口包含一个称为进程的方法,需要编写代码块来拦截请求。在客户端,此方法在将请求发送到服务器之前验证/处理请求,并且在服务器端,此方法在评估请求的主体之前执行。
创建请求拦截器
可以按照以下步骤创建请求拦截器。
第1步 - 创建
HttpRequestInterceptor
的对象通过实现其抽象方法过程来创建
HttpRequestInterceptor
接口的对象。HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { //Method implementation . . . . . };
第2步 - 实例化CloseableHttpClient对象
通过将以上创建的拦截器添加到它来构建自定义的
CloseableHttpClient
对象,如下所示 -//Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).build();
使用此对象,可以照常执行请求执行。
示例
以下示例演示了请求拦截器的用法。在此示例中,创建了一个HTTP GET请求对象,并添加了三个标头:
sample-header
,demoheader
和test-header
。在拦截器
processor()
方法中,验证发送请求的头部; 如果这些标头中的任何一个是sample-header
,我们尝试删除它并显示特定请求的标头列表。import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HttpContext; public class InterceptorsExample { public static void main(String args[]) throws Exception{ //Creating an HttpRequestInterceptor HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if(request.containsHeader("sample-header")){ System.out.println("Contains header sample-header, removing it.."); request.removeHeaders("sample-header"); } //Printing remaining list of headers Header[] headers= request.getAllHeaders(); for (int i = 0; i<headers.length;i++){ System.out.println(headers[i].getName()); } } }; //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(requestInterceptor).build(); //Creating a request object HttpGet httpget1 = new HttpGet("https://www.kaops.com/"); //Setting the header to it httpget1.setHeader(new BasicHeader("sample-header","My first header")); httpget1.setHeader(new BasicHeader("demo-header","My second header")); httpget1.setHeader(new BasicHeader("test-header","My third header")); //Executing the request HttpResponse httpresponse = httpclient.execute(httpget1); //Printing the status line System.out.println(httpresponse.getStatusLine()); } }
执行上面示例代码,得到以下结果:
Contains header sample-header, removing it.. demo-header test-header HTTP/1.1 200 OK
响应拦截器
HttpResponseInterceptor
接口表示响应拦截器。该接口包含一个称为process()
的方法。在此方法中,需要编写代码块来拦截响应。在服务器端,此方法在将响应发送到客户端之前验证/处理响应,在客户端,此方法在评估响应主体之前执行。
创建响应拦截器
可以按照以下步骤创建响应拦截器 -
第1步 - 创建HttpResponseInterceptor的对象
通过实现其抽象方法过程来创建
HttpResponseInterceptor
接口的对象。HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { //Method implementation . . . . . . . . } };
第2步 - 实例化CloseableHttpClient对象
通过向其添加上面创建的拦截器来构建自定义的CloseableHttpClient
对象,如下所示 -//Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build();
使用此对象,可以照常执行请求执行。
示例
以下示例演示了响应拦截器的用法。在此示例中,向处理器中的响应添加了三个标头:
sample-header
,demo-header
和test-header
。
执行请求并获得响应后,使用getAllHeaders()
方法打印响应的所有标头的名称。
在输出中,可以观察列表中三个标题的名称。import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; public class ResponseInterceptorsExample { public static void main(String args[]) throws Exception{ //Creating an HttpRequestInterceptor HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { System.out.println("Adding header sample_header, demo-header, test_header to the response"); response.setHeader("sample-header", "My first header"); response.setHeader("demo-header", "My second header"); response.setHeader("test-header", "My third header"); } }; //Creating a CloseableHttpClient object CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build(); //Creating a request object HttpGet httpget1 = new HttpGet("https://www.kaops.com/"); //Executing the request HttpResponse httpresponse = httpclient.execute(httpget1); //Printing remaining list of headers Header[] headers = httpresponse.getAllHeaders(); for (int i = 0; i<headers.length;i++){ System.out.println(headers[i].getName()); } } }
执行上面示例代码,得到以下结果:
On executing the above program generates the following output. Adding header sample_header, demo-header, test_header to the response Accept-Ranges Access-Control-Allow-Headers Access-Control-Allow-Origin Cache-Control Content-Type Date Expires Last-Modified Server Vary X-Cache sample-header demo-header test-header
RestTemplate
实现org.springframework.http.client.ClientHttpRequestInterceptor接口,跟httpClient拦截器的原理类似,只是略有不同
public class RestTemplateIntercetor implements ClientHttpRequestInterceptor { private static Logger logger = LoggerFactory.getLogger(RestTemplateIntercetor.class); private static String NOTICE_MESSAGE_HOST = "www.zjzr.com.cn"; @Override public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { String authority = httpRequest.getURI().getAuthority(); if(NOTICE_MESSAGE_HOST.equals(authority)){ HttpHeaders headers = httpRequest.getHeaders(); boolean contains = headers.containsKey("token"); if(!contains){ logger.warn("您对www.zjzr.com.cn的访问没有认证标识token,有可能被网关拦截无权访问,请注意"); } } //继续执行请求 return clientHttpRequestExecution.execute(httpRequest,bytes); } }
配置文件
META-INFO/spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.ruijie.springframework.core.configuration.HttpAutoConfiguration
设置自动化配置类 HttpAutoConfiguration
@Configuration public class HttpAutoConfiguration { @Bean @ConditionalOnClass(HttpRequestInterceptor.class) public HttpRequestInterceptor HttpClientRequestInterceptor(){ return new HttpClientRequestInterceptor(); } @Bean @ConditionalOnClass(ClientHttpRequestInterceptor.class) public ClientHttpRequestInterceptor clientHttpRequestInterceptor(){ return new RestTemplateIntercetor(); } @Bean @ConditionalOnBean(ClientHttpRequestInterceptor.class) public RestTemplate restTemplate(ClientHttpRequestInterceptor clientHttpRequestInterceptor){ RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.singletonList(clientHttpRequestInterceptor)); return restTemplate; } @Autowired private ConfigurableEnvironment configurableEnvironment; @PostConstruct public void init(){ String property = configurableEnvironment.getProperty("token"); HttpClientUtil.setToken(property); } }
这样 我们在使用HttpClientUtil或resttemplate的时候 ,拦截器就会生效,验证Token是否存在,并且给出相应提示或抛出异常.
更多相关内容 -
Angular8 Http拦截器简单使用教程
2020-10-16 13:20:02主要介绍了Angular8 Http拦截器简单使用教程,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下 -
Vue+axios 实现http拦截及路由拦截实例
2020-08-30 17:18:33主要介绍了Vue+axios 实现http拦截及路由拦截 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 -
http拦截工具(HTTPAnalyzerStdV5)
2013-11-22 17:40:21http拦截工具(HTTPAnalyzerStdV5) -
vue+axios 前端实现登录拦截的两种方式(路由拦截、http拦截)
2020-10-17 20:09:20本文通过实例代码给大家介绍了vue+axios 前端实现登录拦截的方法,主要通过路由拦截和http拦截,具体实例代码大家跟随小编一起通过本文学习吧 -
详解Angular.js中$http拦截器的介绍及使用
2020-10-19 14:19:47拦截器就是在目标达到目的地之前对其进行处理以便处理结果更加符合我们的预期,下面这篇文章主要给大家介绍了关于Angular.js中$http拦截器的介绍及使用的相关资料,文中介绍的非常详细,需要的朋友可以参考学习。 -
详解AngularJS中的http拦截
2020-10-22 21:03:53主要为大家详细介绍了AngularJS中的http拦截,$http服务允许我们与服务端交互,有时候我们希望在发出请求之前以及收到响应之后做些事情。即http拦截,需要的朋友可以参考下 -
Android的OkHttp包中的HTTP拦截器Interceptor用法示例
2020-09-02 00:59:58拦截器是OkHttp处理HTTP请求方面所具有的一个强大特性,这里我们就来看一下Android的OkHttp包中的HTTP拦截器Interceptor用法示例,需要的朋友可以参考下 -
angular 详解HTTP拦截器 看这一篇就够了
2021-04-08 14:17:08HTTP拦截器 前面我们介绍了Angular 全家桶中 HTTP 部分的基础用法,能够满足开发中的基本需求。为了让我们的教程更贴近实战,拦截器是我们绕不过的话题。 拦截器可以用一种常规的、标准的方式对每一次 HTTP的请求/...HTTP拦截器
前面我们介绍了Angular 全家桶中 HTTP 部分的基础用法,能够满足开发中的基本需求。为了让我们的教程更贴近实战,拦截器是我们绕不过的话题。
拦截器可以用一种常规的、标准的方式对每一次
HTTP
的请求/响应任务执行从认证到记日志等很多种隐式任务。
如果没有拦截机制,那么开发人员将不得不对每次HttpClient
调用显式实现这些任务。比如每次设置请求头中的token
。编写拦截器
要实现拦截器,就要实现一个实现了
HttpInterceptor
接口中的intercept()
方法的类。生成一个
HeroInterceptor
:ng g interceptor http-study/interceptors/hero
默认代码长这样:
// hero.interceptor.ts import { Injectable } from '@angular/core'; import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class HeroInterceptor implements HttpInterceptor { constructor() {} intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { return next.handle(request); } }
上面代码中的
next
对象表示拦截器链表中的下一个拦截器(在应用中可以设置多个拦截器)。上面的
intercept()
方法什么改动都没做,只是单纯的将请求转发给下一个拦截器(如果有),并最终返回HTTP
响应体的Observable
。为了统一设置请求头,我们需要修改请求。但
HttpRequest
和HttpResponse
实例的属性却是只读(readonly
)的,所以修改前,我们需要先把它克隆一份,修改这个克隆体后再把它传给next.handle()
。const copyReq = request.clone();
// hero.interceptor.ts ... intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const copyReq = request.clone({ // 跟上节在服务中设置请求头一致 headers: request.headers.set('token', 'my-auth-token2').set('self-header', 'test2') }); return next.handle(copyReq); }
这种在克隆请求的同时设置新请求头的操作太常见了,因此它还有一个快捷方式
setHeaders
:const copyReq = request.clone({ setHeaders: { token: 'my-auth-token2', 'self-header': 'test2' } });
拦截器也是一个由
Angular
依赖注入 (DI
)系统管理的服务,也必须先提供这个拦截器类,应用才能使用它。由于拦截器是
HttpClient
服务的依赖,所以必须在提供HttpClient
的同一个(或其各级父注入器)注入器中提供这些拦截器。@NgModule({ imports: [ HttpClientModule // others... ], providers: [{ provide: HTTP_INTERCEPTORS, useClass: HeroInterceptor, multi: true }] })
tips:
multi: true
选项会告诉Angular``````HTTP_INTERCEPTORS
是一个多重提供者的令牌,表示这个令牌可以注入多个拦截器。删除我们原来在具体方法中设置的请求头,来验证拦截器是否设置成功。
大功告成,我们设置的第一个请求拦截器成功~
同时,我们还可以在响应体中设置统一的错误处理提示:
// hero.interceptor.ts intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // ... return next.handle(copyReq).pipe( catchError(err => this.handleError(err)) ); } private handleError(error: HttpErrorResponse) { if (typeof error.error?.code === 'number') { console.error(`服务器端发生错误,状态码:${error.error.code}`); } else { console.error('请求失败'); } return throwError(error); }
这样一来,我们的请求服务中的代码就会简练很多。
多个拦截器
可能在应用中会有多个拦截器,这个时候,我们可以将所有的拦截器抽离成一个单独的文件,提供时,引入文件即可:
// interceptors/index.ts import {HeroInterceptor} from '../http-study/interceptors/hero.interceptor'; import {HTTP_INTERCEPTORS} from '@angular/common/http'; export const httpInterceptorProviders = [ { provide: HTTP_INTERCEPTORS, useClass: HeroInterceptor, multi: true }, ];
依赖注入:
import {httpInterceptorProviders} from './http-study/interceptors'; ... providers: httpInterceptorProviders
Angular
会按照提供它们的顺序应用这些拦截器。 如果提供拦截器的顺序是先 A,再 B,再 C,那么请求阶段的执行顺序就是 A->B->C,而响应阶段的执行顺序则是 C->B->A。用拦截器记录日志
我们的每个请求都会通过拦截器,基于这个特点,我们可以用它来做日志的记录。
ng g interceptor http-study/interceptors/logging
创建一个服务用来记录日志:
ng g s http-study/services/logger
添加两个方法,分别用来存储日志与打印日志,当然,里面的逻辑你可以根据需求自己定义:
// logger.service.ts export class LoggerService { logs: string[] = []; private log(msg: string): void { console.log(msg); } add(msg: string): void { this.logs.push(msg); this.log(msg); } }
在
logging
拦截器中注入LoggerService
并实现记录逻辑:// logging.interceptor.ts import { Observable } from 'rxjs'; import {LoggerService} from '../services/logger.service'; import {finalize, tap} from 'rxjs/operators'; @Injectable() export class LoggingInterceptor implements HttpInterceptor { constructor(private loggerServe: LoggerService) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> { const startTime = Date.now(); // 记录请求开始时间 let status: string; // 记录请求状态 return next.handle(request) .pipe( tap( event => status = event instanceof HttpResponse ? 'succeeded' : '', error => status = 'failed' ), finalize(() => { const elapsedTime = Date.now() - startTime; // 请求最后结束时间 const message = `${request.method} "${request.urlWithParams}" ${status} in ${elapsedTime} ms.`; this.loggerServe.add(message); }) ); } }
RxJS
的tap
操作符会捕获请求成功了还是失败了,finalize
操作符无论在响应成功还是失败时都会调用,然后把结果汇报给LoggerService
。
这个拦截器不会对请求与相应做任何修改,原样发送给调用者。(最后别忘了提供这个拦截器)最后我们的效果应该是这样的:
拦截器实现缓存
拦截器还可以自行处理请求,而不用转发给
next.handle()
。利用这一点特性,我们可以做缓存请求和响应,以便提升性能。创建一个
caching
拦截器:ng g interceptor http-study/interceptors/caching
在实现拦截器逻辑之前,我们先来定义一个
Caching
接口:// caching.ts export interface Caching { get(req: HttpRequest<any>): HttpResponse<any> | nill; put(req: HttpRequest<any>, res: HttpResponse<any>): void; }
get()
方法用来获取req
请求对应的响应对象;
put()
方法用于保存req
请求对应的响应对象。另外,我们还需要定义一个
CachingEntry
接口用来保存已缓存的响应对象。
同时定义一个常量用来设定缓存的有效期时间:// caching.ts export interface CachingEntry { url: string; // 被缓存的请求地址 response: HttpResponse<any>; // 被缓存的响应对象 entryTime: number; // 响应对象被缓存的时间,用于判断缓存是否过期 } // 设置最长缓存时间为3s export const MAX_CACHE_AGE = 3000;
现在,我们来实现一个
CachingService
服务,用来实现我们Caching
接口:ng g s http-study/services/caching
// caching.service.ts import { Injectable } from '@angular/core'; import {Caching, CachingEntry, MAX_CACHE_AGE} from '../interfaces/caching'; import {HttpRequest, HttpResponse} from '@angular/common/http'; import {LoggerService} from './logger.service'; @Injectable() export class CachingService implements Caching{ // 定义一个map,用于保存缓存,key值是url cacheMap = new Map<string, CachingEntry>(); // 注入开始的日志拦截器 constructor(private loggerServe: LoggerService ) { } // 获取已缓存的响应体 get(req: HttpRequest<any>): HttpResponse<any> | null { // 试图获取缓存 const entry = this.cacheMap.get(req.urlWithParams); // 判断是否被缓存,如没有直接返回null if (!entry) { return null; } // 判断是否过期 const isExpired = Date.now() - entry.entryTime > MAX_CACHE_AGE; // 添加日志 this.loggerServe.add(`${req.urlWithParams} is Expired: ${isExpired}`); // 有缓存且未过期,返回响应体 return isExpired ? null : entry.response; } // 添加缓存 put(req: HttpRequest<any>, res: HttpResponse<any>): void { // 创建CachingEntry对象 const entry: CachingEntry = { url: req.urlWithParams, response: res, entryTime: Date.now() }; // 添加保存日志 this.loggerServe.add(`Save ${entry.url} response into cache`); // 保存缓存 this.cacheMap.set(entry.url, entry); // 删除过期缓存 this.deleteExpiredCache(); } private deleteExpiredCache(): void { this.cacheMap.forEach((entry: CachingEntry) => { if (Date.now() - entry.entryTime > MAX_CACHE_AGE) { this.cacheMap.delete(entry.url); } }); } }
万事俱备,只差实现
CachingInterceptor
了。// caching.interceptor.ts @Injectable() export class CachingInterceptor implements HttpInterceptor { // 首先注入CachingService服务 constructor(private cachingServe: CachingService) {} intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 判定是否需要缓存,如不需要缓存,直接转给下一个拦截器 if (!this.isCacheable(request)) { return next.handle(request); } // 获取缓存 const cachingRes: HttpResponse<any> = this.cachingServe.get(request); // 如果有缓存,则直接返回一个缓存的Observable, 否则就需要发送请求,并将响应结果缓存 return cachingRes ? of(cachingRes) : this.sendRequest(request, next); } private sendRequest(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( tap(event => { if (event instanceof HttpResponse) { this.cachingServe.put(req, event); // 更新缓存 } }) ); } private isCacheable(req: HttpRequest<any>): boolean { // 这里简单判定了一下,可以根据自己需求去实际判断 return req.method === 'GET'; } }
到此为止,我们就实现了
CachingInterceptor
全部功能,记得提供这个拦截器。从上面的效果可以看出,当我们第一次请求的时候缓存了相应结果,第二次是直接获取的缓存,当与第一请求间隔3s后,再次请求时,缓存已过期,所以就再次发送了请求。同时,从浏览器的 Network 中也能看到只发送了真正的两次请求。
用拦截器来请求多个值
HttpClient.get()
方法通常会返回一个可观察对象,拦截器可以把它改成一个可以发出多个值的可观察对象。我们在拦截器中加一段判定:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // ... // 先获得缓存 if (request.headers.get('x-refresh')) { const results$ = this.sendRequest(request, next); return cachingRes ? results$.pipe( startWith(cachingRes) ) : results$; } // 缓存或者直接请求 return cachingRes ? of(cachingRes) : this.sendRequest(request, next); }
这样一来,如果没有缓存值,拦截器直接返回
results$
,否则先将缓存的响应加入到result$
的管道中,使用重组后的可观察对象进行处理,并发出两次。先立即发出一次缓存的响应体,然后发出来自服务器的响应。总结
cli
工具生成拦截器是没有简写方式的,应该是ng g interceptor xxx
;- 拦截器请求顺序是按照配置顺序执行,响应拦截则是相反的顺序;
- 用拦截器做请求缓存能优化性能,是个好东西;
- 必须在提供
HttpClient
的同一个(或其各级父注入器)注入器中提供拦截器。
欢迎关注我的公众号,公众号将第一时间更新angular教程:
-
Python-socksmon使用您的HTTP拦截代理监视任意TCP流量
2019-08-10 05:39:19socksmon 使用您的HTTP拦截代理监视任意TCP流量 -
Vue--实现登录拦截(Vue、axios、http拦截)
2021-12-10 14:47:03一、Vue通过router实现登录拦截 1.requireAuth requireAuth属性作用是表明该路由是否需要登陆验证,在进行全局拦截时,通过该属性进行判断,该属性包含在meta属性中。 import Vue from 'vue' import Router from '...许多页面在访问之前是需要登陆验证的,如果用户没有登录,则需要用户跳转到登陆页面进行登录。
结合自身练习以及资料进行整理,提供以下几种方式一、Vue通过router实现登录拦截
1.requireAuth
requireAuth属性作用是表明该路由是否需要登陆验证,在进行全局拦截时,通过该属性进行判断,该属性包含在meta属性中。
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) routes=[ { path:'/', name:'Default', redirect:'/home', component:Home, meta:{ requireAuth:true //此时表示进入这个路由是需要登录的 } }, { name:'login', path:'/login' } ]
2.router.beforeEach
beforeEach时router的钩子函数,该函数在进入每个网页之前调用,该函数接收三个参数:
①from:即将离开的路由
②to:即将要跳转的路由
③next:跳转方法,在beforeEach函数中作为结束语句调用,以实现页面跳转。
next(false):中断当前的导航。如果浏览器的url改变了(可能是手动或浏览器按钮后退),那么url地址会重置到from路由对应的地址。
next(’/’)或者next({path:’/’}):跳转到一个不同的地址。当前导航被中断,然后进行一个新的导航。要确保next方法被调用,否则钩子就不会被resolved
router.beforeEach((from,to,next)=>{ if(to.meta.requireAuth){//判断跳转的路由是否需要登录,如果前端没有登录信息则直接拦截,如果有则判断后端是否正常登录(防止构造参数绕过) if(store.state.token){//vuex.state判断token是否存在 即是否有用户登录 next()//已登录进行跳转 }}else{ next({ path:'/login', query:{redirect:to.fullPath}//将跳转的路由path作为参数,登陆成功后跳转到该路由,这里的to.fullPath是带的一个参数传给登陆页面,登录之后要跳转的路由 }) } }else{ next() } }
登陆完成后,在登陆中改变vuex的状态
login () { var _this = this this.$axios.post('/login', { username: this.loginForm.username, password: this.loginForm.password }).then(resp => { if (resp.data.code === 200) { var data = resp.data _this.$store.commit('login', data) var path = _this.$route.query.redirect _this.$router.replace({path: path === '/' || path === undefined ? '/admin/dashboard' : path}) } else { this.$alert(resp.data.data, '提示', { confirmButtonText: '确定' }) } }).catch(failResponse => { }) }
二、拦截器(通过使用axios拦截器)
如果要统一处理所有的http请求和响应,就需要使用axios的拦截器。通过配置http response inteceptor,当后端接口返回错误信息,让用户重新登陆
// http request 拦截器 axios.interceptors.request.use( config => { if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token config.headers.Authorization = `token ${store.state.token}`; } return config; }, err => { return Promise.reject(err); }); // http response 拦截器 axios.interceptors.response.use( response => { return response }, error => { if (error) { store.commit('logout') router.replace('/login') } // 返回接口返回的错误信息 return Promise.reject(error) })
三、http拦截
这里引入的element ui框架,结合element中loading和message组件来处理的。可以单独建立一个http的js文件处理axios,再到main.js中引入。
/** * http配置 */ // 引入axios以及element ui中的loading和message组件 import axios from 'axios' import { Loading, Message } from 'element-ui' // 超时时间 axios.defaults.timeout = 5000 // http请求拦截器 var loadinginstace axios.interceptors.request.use(config => { // element ui Loading方法 loadinginstace = Loading.service({ fullscreen: true }) return config }, error => { loadinginstace.close() Message.error({ message: '加载超时' }) return Promise.reject(error) }) // http响应拦截器 axios.interceptors.response.use(data => {// 响应成功关闭loading loadinginstace.close() return data }, error => { loadinginstace.close() Message.error({ message: '加载失败' }) return Promise.reject(error) }) export default axios
-
详解为Angular.js内置$http服务添加拦截器的方法
2020-10-20 19:57:31所谓拦截器就是在目标达到目的...Angular的$http拦截器是通过$httpProvider.interceptors数组定义的一组拦截器,每个拦截器都是实现了某些特定方法的Factory。本文就介绍了为Angular.js内置$http服务添加拦截器的方法。 -
Angular Http拦截器(HttpInterceptor)的使用
2020-03-27 15:18:41Http拦截器就是拦截发出的请求,对其进行统一添加额外处理,然后放行; 对响应进行拦截并作出业务上的判断,决定是否给与返回 1.定义req.interceptor.ts文件(以‘.interceptor.ts’作为后缀) import { Injectable } ...Http拦截器就是拦截发出的请求,对其进行统一添加额外处理,然后放行;
对响应进行拦截并作出业务上的判断,决定是否给与返回
1.定义req.interceptor.ts文件(以‘.interceptor.ts’作为后缀)import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; const ignoreToken = ['login', 'logout', 'table']; @Injectable() export class CommonInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { //请求拦截 console.log(req); return next.handle(req).pipe( tap( //响应拦截 event => { console.log(event); if (event instanceof HttpResponse) { if (event.status >= 500) { // 跳转错误页面 } } }, error => { console.log(error); // token过期 服务器错误等处理 }) ); } }
2.注入在app模块,在providers数组种添加
{ provide: HTTP_INTERCEPTORS, useClass: CommonInterceptor, //自定义拦截器的类名 multi: true //这是必须的,因为它会告诉 Angular 这个 HTTP_INTERCEPTORS 表示的是一个数组,而不是单个的值。 }
3.运行结果
请求拦截:
响应拦截
-
AngularJS http拦截器依赖注入$http
2016-09-24 22:58:33如何在AngularJs中配置http拦截器。 -
vue+axios 前端实现登录拦截(路由拦截、http拦截)
2017-11-17 10:49:48一、路由拦截 登录拦截逻辑 第一步:路由拦截 首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由, 否则就进入登录... -
angular 拦截器_在Angular中绕过Http拦截器的超级简单技巧
2020-08-16 01:52:46angular拦截器Recently, I have been working on a task, regarding AWS S3 bucket file uploading using Angular and preSigned URLs. In that project, I have used HTTP interceptor to handle my request to ... -
Vue+axios 实现http拦截及路由拦截
2018-04-25 17:41:05现如今,每个前端对于Vue都不会陌生,Vue框架是如今最流行的前端框架之一,... 技术栈vue2.0vue-routeraxios 拦截器 首先我们要明白设置拦截器的目的是什么,当我们需要统一处理http请求和响应时我们通过设置拦截器处... -
vue实战:HTTP路由拦截
2020-04-10 15:16:31vue中有“三霸”:拦截器interceptor、路由守卫meta、导航守卫beforeEach、beforeRouterEnter(Update)。 他们都有一个共同的作用(...也可能是唯一的作用) —— 在路由变更前做一次判断,或取或舍,或添加token、... -
浅析AngularJs HTTP响应拦截器
2020-11-24 01:55:58通过实现 request 方法拦截请求: 该方法会在 $http 发送请求道后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configuration object)作为参数,然后必须返回配置对象或者 promise... -
angular2的http拦截器、angular4中的httpclient拦截器
2018-10-14 13:26:37angular2中的http拦截器 angular2拦截器看的比较好的博客 angular4中的httpclient拦截器 从angular4.3.4以后官方网站给出了官方的拦截器定义方法,请参考官网4.4.7版本 ... -
axios使用拦截器统一处理所有的http请求的方法
2021-01-19 16:50:04http request拦截器 // 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject... -
vue-resource请求实现http登录拦截或者路由拦截的方法
2020-12-10 17:10:20本文介绍了vue-resource请求实现http登录拦截或者路由拦截的方法,分享给大家,具体如下: 项目需求 项目是前后台分离,前端负责数据对接,以及业务逻辑的处理,后台只需要给相应的接口即可 后台会控制接口的授权... -
快速学习AngularJs HTTP响应拦截器
2020-11-22 08:01:55任何时候,如果我们想要为请求添加全局功能,例如身份认证、错误处理等,在请求发送给服务器...该方法会在 $http 发送请求后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configura -
LSP 劫持 TCP协议 UDP协议 HTTP协议 拦截 VS 2013
2018-10-24 22:03:40LSP 劫持 TCP协议 UDP协议 HTTP协议 拦截 VS 2013 VC开发 例子有 TCP 拦截 修改 转发 UDP 拦截 转发 修改 HTTP 修改 转发