如何阻止Interceptor覆盖授权标头。 我的应用程序中有一个通用拦截器 除了抛弃拦截器并手动为每个http请求发送标头之外,该问题的解决方案是什么
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
return next.handle(req);
}
}
我有一个提供另一个访问令牌的API,每当用户转到CleaningComponent时,我都需要在标头中发送它,但是拦截器会将该令牌替换为本地存储中的令牌。 旁注:某些API调用在CleaningComponent中需要拦截器发送的访问令牌本地存储,因此我无法从此组件中完全关闭它。
export class CleaningComponent implements OnInit {
chosenFile = null;
elcUserDetail: any;
access_token: any;
constructor(private auth: AuthService, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.data.subscribe((data: any)=> {
this.elcUserDetail = data.elcUserDetailResolver.body.data;
this.access_token = this.elcUserDetail.access_token;
console.log(this.access_token);
})
setTimeout(() => {
this.auth.uploadListCleaningFile(this.access_token).subscribe((res: any)=>{
console.log(res);
},(err: any)=>{
console.log(err);
});
}, 1000);
}
我在其中设置新标题的身份验证服务
uploadListCleaningFile(token: any) {
const headers = new HttpHeaders({
'Authorization': 'Bearer ' + token
});
console.log(headers);
return this.http.post(this.uploadListCleaningFileApi, null, {headers: headers});
}
答案 0 :(得分:0)
您可以在添加新标题之前检查标题是否存在,如下所示:
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
const headersToAppend = {};
// Here check if the request has the header already
if(!req.headers.has('Authorization')){
headersToAppend['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`
}
req = req.clone({
setHeaders: headersToAppend
});
return next.handle(req);
}
}
答案 1 :(得分:0)
@cupusasa只需检查您不想从 url
设置auth token
的 localStorage
。>
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
if (req.url == "specificURL") {
req = req.clone({
headers: {
"Content-Type": "application/json"
}
});
} else {
req = req.clone({
headers: {
Authorization: `Bearer ${localStorage.getItem('access_token')}`
}
});
}
return next.handle(req);
}
}