【问题标题】:Get authorization header from Http Interceptor从 Http Interceptor 获取授权标头
【发布时间】:2018-04-17 14:56:55
【问题描述】:

我已授权将令牌直接放入headers。我现在如何从 Angular 4 Http Interceptor 获取此令牌?

很遗憾,console logs 下面的任何一个都不包含此标头:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    //const changedReq = req.clone({headers: req.headers.set('Authorization', 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkB3cC5wbCIsImV4cCI6MTUxMDY2NDM0M30.0iBktdr4-1EzTi1iaQOOfguK7HGVJF7JYkB-AF3uZgJrmKnVESAyKkHoNRzum1Pq5xZ6GJaZC9cbZQ2umMSfLA')});
    console.log('req', req);
    return next.handle(req).do((event: HttpEvent<any>) => {
      console.log('event', event);
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
          this.ehs.setService(err.status, err.error);
          // redirect to login
      }
    });
  }

【问题讨论】:

  • 尝试在 HttpResponse 分支中记录 event.headers

标签: angular header authorization interceptor angular-http-interceptors


【解决方案1】:

HttpHeadersMap instance 的包装器,因此console.log 输出中不会显示现有的标头,因为Map 的值不会暴露。

可以从HttpHeaders 实例中检索标头,正如其 API 所建议的那样:

req.headers.get('authorization');

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2013-09-04
    • 2015-05-30
    • 2016-04-24
    • 2014-07-31
    相关资源
    最近更新 更多