[英]Angular2 's Http.post is not returning headers in the response of a POST method invocation
[英]How to get http POST's response's headers in Angular 8
所以我有一個像下面這樣的帖子,我發送一個 POST 請求來登錄並且響應是空的——這很好,正如預期的那樣——但我需要訪問“授權”header。
我沒有找到任何訪問方式。
const data = {email: "email", password: "password"};
this.http.post(`/login`, data).pipe(
tap(resp => {
console.log(resp); // it will be an empty string
return resp;
})).subscribe((resp: any) => {
console.log(resp.headers.get('Authorization')); // error: Cannot read property 'headers' of null
});
更新受 TheUnreal 的回答啟發,我添加了選項
this.http.post(`/login`, data, {observe: 'response'} )...
現在我可以訪問一些標題,例如“Cache-Control”。
可能我需要從服務器端表達標題的 rest
Sam Walpole 在評論部分是對的,這個問題的大部分都在他提供的鏈接上得到了回答 - 退房。
您可以通過將以下選項傳遞給您的 http 方法來獲取請求的標頭和其他信息:
return this.http.post('YOUR URL', PAYLOAD, {
observe: 'events'
})
按照 TheUnreal 的建議在帖子中添加選項,但對我來說需要“響應”
this.http.post(`/login`, data, {observe: 'response'} )
在服務器端,需要設置和公開標頭Access-Control-Allow-Headers和Access-Control-Expose-Headers 。
有點跑題了,但是-可能對某人有所幫助-這就是我們的配置在 Java Spring 中的樣子
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Headers", "Origin,Accept", "X-Requested-With", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers"));
configuration.addExposedHeader("Authorization");
Sam Walpole 在這個問題的評論部分是正確的,這個問題的大部分都在他提供的鏈接上得到了回答 - 退房。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.