nestjs - Nestjs拦截器如何捕获http 401错误并重新提交原始请求
问题描述
我需要编写一个http头拦截器来添加授权头,如果出现401错误,请提交另一个新令牌的请求,然后用新令牌重新提交原始请求。
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const response = context.switchToHttp().getResponse();
return next.handle().pipe(
catchError(async error => {
if (error.response.status === 401) {
const originalRequest = error.config;
var authRes = await this.authenticationService.getAccessToken();
this.authenticationService.accessTokenSubject.next(authRes.access_token);
// I need to resubmit the original request with the new token from here
// but return next.handle(originalRequest) doesn't work
}
return throwError(error);
}),
);
}
但是 next.handle(originalRequest) 不起作用。如何在拦截器中重新提交原始请求?非常感谢您的帮助。
解决方案
我刚刚遇到了一个类似的问题,我可以从异常过滤器中捕获异常,但在拦截层中不能这样做。
于是我查了一下说明书,发现上面写着:
Any exception thrown by a guard will be handled by the exceptions layer
(global exceptions filter and any exceptions filters that are applied to the current context).
因此,如果异常是从 AuthGuard 上下文中抛出的(包括 AuthService 中的 validate 方法),最好通过像这样扩展 Authguard 来移动附加逻辑:
export class CustomizedAuthGuard extends AuthGuard('strategy') {
handleRequest(err, user, info, context, status) {
if (err || !user) {
// your logic here
throw err || new UnauthorizedException();
}
return user;
}
}
或者只是使用自定义的异常过滤器。
推荐阅读
- python - Python中列表列表的列表理解
- mysql - MySQL pass parents field to subquery without using JOINS
- jquery - How to fix the web page slow down issue in datatables?
- swift - RxSwift:确保订阅关闭中的当前线程
- c - Trouble linking own application using ffmpeg/libav
- c# - CommandInvokationFailure:Gradle 构建失败(同样的错误一次又一次)
- fortran - How to fix solution with double integration
- url-rewriting - Weblogic 12.2 + url rewriting = response blocked
- google-drive-api - How to create service account for google drive api for NOT G Suite account?
- javascript - the loop doesnt run on the array's objects