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