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

Nel*_*ves 5 httpclient ionic-framework angular

我正在使用一个登录端点,它返回一个不记名令牌作为响应标头,正如我在“网络”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...)
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用 HttpClient 实例从响应中打印“标题”时:

  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);
        }
      );
  }
Run Code Online (Sandbox Code Playgroud)

我得到了一个完全不同的结构:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}
Run Code Online (Sandbox Code Playgroud)

我也尝试了 get(headerName) 方法并得到了空值。我错过了什么?如何从我的回复中获取“授权”标头?

Cha*_*dru 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);
        }
        );
}
Run Code Online (Sandbox Code Playgroud)


小智 2

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

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

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