美文网首页Ios@IONIC
Angular2 http获取response header对象

Angular2 http获取response header对象

作者: SuperBinlin | 来源:发表于2017-04-26 14:47 被阅读650次

很多时候需要获取响应头来进行一些操作,比如获取响应头中的Date来缓存请求时间,获取自定义的token进行用户登录验证等等。

一般请求头

如何拿到上面的信息呢,这里以获取Date值举例,相信很多人发现,在成功回调中打印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属性呢,因为如果你与服务端同域,你可以获得所有header对象属性,但是如果不同域的话,需要在服务端设置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

这样设置完后 就能通过res.header.get('Date')获取响应头中Date的值了。

相关文章

网友评论

    本文标题:Angular2 http获取response header对象

    本文链接:https://www.haomeiwen.com/subject/ynpizttx.html