我需要對403 Forbidden HTTP狀態(獲取/刷新)JWT令牌作出反應(在攔截器類中),然後使用新令牌重試該請求。Angular 4.3 - HTTP攔截器 - 刷新JWT令牌
在下面的代碼中,當服務器返回錯誤響應時,它返回到成功回調(而不是像我預期的那樣進入錯誤回調),事件是typeof對象(對錯誤響應的反應無用)。事件對象如下所示: {type:0}。
問:
- 如何正確處理httpErrorResponse(403禁止)在 HttpInterceptor當我需要刷新的accessToken並重試http請求?
import {
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
class JWTInterceptor implements HttpInterceptor {
constructor(private tokenService: TokenService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let myHeaders = req.headers;
if (this.tokenService.accessToken) {
myHeaders = myHeaders.append('Authorization',`${this.tokenService.accessToken.token_type} ${this.tokenService.accessToken.access_token}`)
}
const authReq = req.clone({headers: myHeaders});
return next.handle(authReq).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// success callback
}
}, (err: any) => {
if (err instanceof HttpErrorResponse {
if (err.status === 403) {
// error callback
this.tokenService.obtainAccessToken()
}
}
})
.retry(1);
}
}
它解決我的問題的一部分 - 在抓我現在可以訪問HttpErrorResponse和調用我的刷新/獲取令牌邏輯 - 謝謝你。但是當我調用**。retry(1)**時,新的http請求不會再通過攔截器(因此JWT頭文件不會添加到新的調用中) – kuceraf
您需要在刷新函數中執行的操作是返回'Observable '。然後在該catch塊中返回該刷新函數的調用,並將其添加到攔截器。例如更新答案。 – Lansana