typescript 如何在 Angular 5 中使用 HttpClient 访问响应标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47753885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I access response headers using HttpClient in Angular 5?
提问by Florian
I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.
我在 Angular 5 中编写了一个身份验证服务,它使用 HttpClient 类向我的后端发出 POST 请求。后端通过发送 JWT 不记名令牌进行响应。
My request looks like this:
我的请求是这样的:
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
})
.toPromise()
.then(response => {
console.log(response);
return response;
});
}
}
How do I access the authorization header of the response?
如何访问响应的授权标头?
When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.
当我将响应写入控制台时,如上所示,它显示“空”。我知道错误不在后端,因为我捕获了流量并且后端确实发送了不记名令牌。
Any help is very much appreciated.
很感谢任何形式的帮助。
回答by LLai
To access the full response (not just the body of the response), you must pass the observe: 'response'
parameter option in your http request. Now you can access the headers with res.headers
要访问完整的响应(不仅仅是响应的正文),您必须observe: 'response'
在 http 请求中传递参数选项。现在您可以访问标题res.headers
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json'),
observe: 'response'
})
.map(res => {
let myHeader = res.headers.get('my-header');
});