【问题标题】:Angular HttpClient - Get headers from responseAngular HttpClient - 从响应中获取标头
【发布时间】:2019-03-04 21:50:48
【问题描述】:

我知道对此有很多已回答的问题,但没有一个对我有用。

我正在尝试执行以下调用:

this.http.options("http://...", {observe: 'response'}).subscribe((data: HttpResponse<any>) => console.log(data))

但是,该输入的标题字段为空! :

HttpResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: 

"http://...", ok: true, …}
body: ""
headers: HttpHeaders
lazyInit: ƒ ()
lazyUpdate: null
normalizedNames: Map(0)
size: (...)
__proto__: Map
[[Entries]]: Array(0)
length: 0
__proto__: Object
ok: true
status: 200
statusText: "OK"
type: 4
url: "http:/..."
__proto__: HttpResponseBase

但如果我使用 Postman 进行相同的调用,我会得到以下标题!

Allow →PUT, HEAD, OPTIONS, GET
Content-Length →0
Content-Type →text/html; charset=utf-8
Date →Fri, 28 Sep 2018 21:29:22 GMT
Server →Google Frontend
X-Cloud-Trace-Context →6627df99d34998ddeadcdcf7a2b132be;o=1

我需要获取“允许”标题,但我似乎无法做到。

请帮忙

【问题讨论】:

标签: angular header httpclient


【解决方案1】:

我发现你的问题有两个问题:

  1. 使用 Angular 的 HttpClient,响应标头是延迟加载的,这意味着您需要尝试 get 值才能真正看到它存在。例如:

     const allowValue = response.headers.get('allow');
    
  2. 要允许您的客户端 JavaScript 访问此标头,您需要设置一个响应标头(当然是服务器端的)。以下行显示了标题和需要设置的值:

     Access-Control-Expose-Headers: allow
    

您可以在 MDN 上阅读更多相关信息:Access-Control-Expose-Headers

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 2018-01-12
    • 1970-01-01
    • 2018-07-31
    • 2019-02-25
    • 2019-12-21
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多