在 HttpClient 拦截器中进行全局授权 Header

Making Global Authorization Header in HttpClient Interceptor

我正在我的应用程序中进行全局授权 header。我使用了拦截器,所以我不会在我的 get() 函数中声明授权 header。我是否正确地实现了拦截器,因为当我调用 get() 函数时,它仍然要求令牌。它说未提供令牌。我的 auth.interceptor 有问题吗?我应该在每个 get() 函数中声明授权 header 不记名令牌吗?我以为每次有请求都会调用拦截器sent/receive?

auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private authService: AuthService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        this.authService = this.injector.get(AuthService);
        const token = this.authService.getToken();
            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

            req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
            return next.handle(req);
        }
}

products.component.ts

getAll() {
    return this.httpClient.get<any>(this.url).map(response => response.json());
    }

你做得对!

拦截器用于拦截所有http调用,您可以更改全局请求。

我觉得问题出在这些条件下。您可以调试并解决它们。

            if (token) {
                req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
            }

            if (!req.headers.has('Content-Type')) {
                req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
            }

也许有些他们返回的是空值!

但如果获取令牌的时间问题,您可以进行异步调用以获取令牌。

this.authService.LoginUser().subscribe(( token) => { 
   if (token) { 
     req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); 
   } 

   if (!req.headers.has('Content-Type')) { 
     req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); 
   } 

   req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); 
   return next.handle(req); 
} 
});