如何从 HttpClient 响应访问标头?(角/离子) [英] How to access headers from a HttpClient response? (Angular / Ionic)

查看:32
本文介绍了如何从 HttpClient 响应访问标头?(角/离子)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的登录端点返回不记名令牌作为响应标头,正如我在网络"Chrome 检查窗口中看到的:

I'm using a login endpoint that returns a bearer token as a response header, as I can see in the "Network" Chrome inspect window:

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 实例从响应中打印标题"时:

However, when I try to print "headers" from the response using a HttpClient instance:

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

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

I get a completely different structure:

HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}

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

I also tried the get(headerName) method and got null. What am I missing? How can I get that "Authorization" header from my response?

推荐答案

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

Are you sure you are adding it as a part of the response? You need to add the header in the response:

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

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

And then you can do what you have been trying. I think headers.get('Authorization') should give you the desired value

这篇关于如何从 HttpClient 响应访问标头?(角/离子)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆