gpt4 book ai didi

error-handling - 在Angular 8中更改 token 后重新发送未经授权的请求

转载 作者:行者123 更新时间:2023-12-03 08:42:10 24 4
gpt4 key购买 nike

我是 Angular 8的新手。
我有一个拦截器:

export class HttpRequestInterceptor implements HttpInterceptor {
private apiAddress = 'http://localhost:1080';
private refreshTokenIsInProgress = false;
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let cloneReq;
//...
// some codes like adding access token to header
//...

cloneReq = request.clone();
return next.handle(cloneReq)
.pipe(
catchError((error: any) => {
if(error.status==401)//means token expired
{
//Here i need help
//Get NEW Token And Replace With previous And Resend Current Request
}
return of(error);
})
)
;
}
}
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true },
];

我的要求是:
return this.http.get(url).subscribe();

如前所述,如果请求返回401(未经授权),则需要从服务器获取新 token (JWT),将其替换为先前的 token ,然后重新发送CURRENT请求;
获取新 token 没有问题!
问题是替换新 token 并重新发送请求;

我搜索和搜索了很多小时的表格,但是...
我以为可以通过使用 retry() retryWhen()来实现此目标,但是它们不能更改请求参数。
谢谢大家

最佳答案

尚未测试代码,但是您可以尝试将请求包装到更高阶的函数中并访问请求对象,还可以递归调用函数,直到满足条件为止。

      const repeatRequest=(cloneReq)=>next.handle(cloneReq)
.pipe(
catchError((error: any) => {
if(error.status==401)//means token expired
req=........ // modify your request here
return repeatRequest(req)
return of(error);
})
)
cloneReq = request.clone();

return repeatRequest(cloneReq)

关于error-handling - 在Angular 8中更改 token 后重新发送未经授权的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60875927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com