gpt4 book ai didi

angular - 在 httpInterceptor 中过滤请求 - Angular 4.3+

转载 作者:太空狗 更新时间:2023-10-29 19:27:59 25 4
gpt4 key购买 nike

我有一个身份验证拦截器,但是,我希望这个拦截器过滤请求,而不是在用户访问不需要用户身份验证的组件(如确认帐户密码等)时应用。关于如何去做的任何例子?这是 auth 拦截器的逻辑:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth token from the service.
let authToken = this.authService.getToken();
let authHeader = 'Bearer ' + authToken;

//For requests that are retried, we always want a fresh copy, else the request will have headers added multiple times.
//So Clone the request before adding the new header.
//NOTE: the cache and pragma are required for IE that will otherwise cache all get 200 requests.
const authReq = request.clone({
setHeaders: {
Authorization: authHeader,
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}

最佳答案

对于这种情况,您请求的 URL 很有帮助。

假设,您的身份验证 url 类似于 auth/login 或 auth/refreshToken,您的资源 api url 类似于 api/users、api/users/123、api/addUser,那么你可以放置一个 if 条件来检查请求的内容。

url匹配的例子:-

 if (request.url.match(/api\//)) { // api call
console.log('api call detected.');
let authToken = this.authService.getToken();
let authHeader = 'Bearer ' + authToken;
const authReq = request.clone({
setHeaders: {
Authorization: authHeader,
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
}
});
return next.handle(authReq);
}
else{ // auth call - you can put esle if conditions if you have more such pattern
console.log('auth call detected.');
return next.handle(request);
}

现在 authentication headers 只会被添加到你的 api-call(我的意思是资源 api-call),其他调用不会被修改。

NB: I've been in backend technology like Java, DBs, etc.. for longer time and now learning angular for the first time, so answered like a mod :P, but the idea was from my last Java project. Hope it helps..!! :)

关于angular - 在 httpInterceptor 中过滤请求 - Angular 4.3+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46821769/

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