如何从HttpClient响应中获取头信息?(Angular/Ionic)

5

我正在使用一个登录终端点,该终端点将承载令牌作为响应标头返回,正如我可以在Chrome检查窗口的“网络”选项卡中看到的那样:

Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:8100
Authorization:Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJuZWxpby5jdXJzb3NAZ21haWwuY29tIiwiZXhwIjoxNTEyNzA3OTQ3fQ.pOR4WrqkaFXdwbeod1tNlDniFZXTeMXzKz9uU68rLXEWDAVRgWIphvx5F_VCsXDwimD8Q04JrxelkNgZMzBgXA
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:188
(etc...)

然而,当我尝试使用HttpClient实例从响应中打印“headers”时:
  authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({"Content-Type": "application/json"});
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response'})
      .subscribe(
        (resp) => {
          console.log("resp-ok");
          console.log(resp.headers);
        },
        (resp) => {
          console.log("resp-error");
          console.log(resp);
        }
      );
  }

我得到了完全不同的结构:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

我还尝试了使用get(headerName)方法,但是返回了null。我错过了什么?我该如何从响应中获取“Authorization”头信息?

尝试使用 angular-2-get-authorization-header 进行操作。 - Anto Antony
4个回答

5
尝试像这样做:

试一试这样:

authenticate(credentials) {
    let creds = JSON.stringify(credentials);
    let contentHeader = new HttpHeaders({ "Content-Type": "application/json" });
    this.http.post(this.LOGIN_URL, creds, { headers: contentHeader, observe: 'response' })
        .subscribe(
        (resp) => {
            let header: HttpHeaders = resp.headers;
            console.log(header.get('Authorization'))
        },
        (resp) => {
            console.log("resp-error");
            console.log(resp);
        }
        );
}

HttpHeaders,而不是Headers。 - Estus Flask
1
类型转换为HttpHeaders对我很有用。谢谢!! - Bhaumik Sathvara
主要的技巧是在请求头中添加observe: 'response'。 - Ali Haider

4
你就快成功了。
原因在于你没有使用headers.get函数。
请改为:
 console.log(resp.headers);

对于这个问题

 console.log(resp.headers.get('Authorization'))

更多信息:

官方文档在此


2

您确定将其作为响应的一部分添加了吗?您需要在响应中添加标题:

public void methodJava(HttpServletResponse response){
  ...
 response.addHeader("access-control-expose-headers", "Authorization");
}

然后你可以做你一直在尝试的事情。我认为headers.get('Authorization')应该给你所需的值。


只是想知道为什么这是被接受的答案?这是Java代码。 - brijmcq

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接