JWT令牌未在angular6中传入标头

问题描述 投票:0回答:1
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let request = req.clone({
      setHeaders: this.getRequestHeaders()
    });
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse && event.status==200) {
      } else 
      console.log('event =', event, ';');
      return event;
    })
    .catch((err: any, caught) => {
      if (err instanceof HttpErrorResponse) {
        let error=err['error']
        // if (err['error'] && (err['error']['status'] == 401) && (err['error']['message']=="Session Expired,please login Again.") || err['error']['message']=="Full authentication is required to access this resource") {
        //   setTimeout(()=>{
        //     this.localStorageService.clearLocalStorage();
        //     return this.router.navigate(['/login']);              
        //   }, 1000);
        // }
        return Observable.throw(error);
      }
    });
  }

  public getRequestHeaders(){
    let token=this.localStorageService.getToken();
    let headers={'Accept':  'application/json'};
    if(token){
      headers['Authorisation']=token;
    }
    return headers;
  }

我已经实现了拦截器服务,但令牌没有通过标头传递,因此没有任何工作。我从本地存储中获取令牌但没有显示任何内容

angular
1个回答
0
投票

要设置标头,您必须像这样创建标头实例。以下是我的例子

  private initAuthHeaders(): Headers {
    const token = this.getLocalToken();
    const headers = new Headers();
    if (token !== null) {
      headers.append('Authorization', 'Bearer ' + token);
    }
    headers.append('Content-Type', 'application/json');
    return headers;
  }
© www.soinside.com 2019 - 2024. All rights reserved.