[英]How to access headers from a HttpClient response? (Angular / Ionic)
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: 我正在使用登录端点返回一个承载令牌作为响应头,我可以在“网络”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...)
However, when I try to print "headers" from the response using a HttpClient instance: 但是,当我尝试使用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);
}
);
}
I get a completely different structure: 我得到一个完全不同的结构:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
lazyInit : ƒ ()
lazyUpdate : null
normalizedNames : Map(0) {}
I also tried the get(headerName) method and got null. 我也尝试了get(headerName)方法并获得了null。 What am I missing?
我错过了什么? How can I get that "Authorization" header from my response?
如何从我的回复中获得“授权”标题?
try like this : 试试这样:
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);
}
);
}
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");
}
And then you can do what you have been trying. 然后你可以做你一直在尝试的事情。 I think headers.get('Authorization') should give you the desired value
我认为headers.get('Authorization')应该给你想要的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.