如何从HttpClient响应中访问标头? (角/离子)

时间:2017-12-07 04:47:17

标签: angular ionic-framework httpclient

我正在使用一个登录端点,它返回一个承载令牌作为响应头,我可以在“网络”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。我错过了什么?如何从我的回复中获得“授权”标题?

3 个答案:

答案 0 :(得分:3)

你快到了。

它无效的原因是您没有使用.get的{​​{1}}功能。

更改此

headers

到此

 console.log(resp.headers);

更多信息:

官方文件here

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:1)

尝试这样:

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);
        }
        );
}