很多時候需要獲取響應(yīng)頭來進(jìn)行一些操作凿歼,比如獲取響應(yīng)頭中的Date來緩存請求時間冗恨,獲取自定義的token進(jìn)行用戶登錄驗(yàn)證等等答憔。
如何拿到上面的信息呢虐拓,這里以獲取Date值舉例傲武,相信很多人發(fā)現(xiàn),在成功回調(diào)中打印header對象中并沒有Date屬性谱轨,如下:
this.http.get(urls).subscribe((res) => {
console.log(res.headers.get('Date'))? ? ? ? ? ? // 獲取date值 輸出null
console.log(res.headers.toJSON()) ? ? ? ? ? ? // 獲取header對象 輸出入下圖
},error => {
.....
})
為什么header對象中只有Content-Type屬性呢土童,因?yàn)槿绻闩c服務(wù)端同域,你可以獲得所有header對象屬性献汗,但是如果不同域的話,需要在服務(wù)端設(shè)置expose_headers楚午。
Before
'^/api/':
allow_credentials: true
origin_regex: true
allow_origin:['*']
allow_headers:['Origin','Accept','Content-Type','Location']
allow_methods:['POST','GET','DELETE','PUT','OPTIONS']
max_age: 3600
After
'^/api/':
allow_credentials: true
origin_regex: true
allow_origin:['*']
allow_headers:['Origin','Accept','Content-Type','Location']
allow_methods:['POST','GET','DELETE','PUT','OPTIONS']
expose_headers:['Origin','Accept','Content-Type','Date']
max_age: 3600
這樣設(shè)置完后 就能通過res.header.get('Date')獲取響應(yīng)頭中Date的值了尿招。