简体   繁体   中英

Angular HttpClient - Get headers from response

I know there are many answered questions to this but none of them has worked to me.

I am trying to do the following call:

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

However the headers field from that input are empty! :

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

But if I do that same call with Postman I get the following headers!

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

I need to get the 'Allow' headers but I don't seem to be able to do it.

Help pls

I see two problems in your question:

  1. Using Angular's HttpClient , response headers are lazy-loaded, which means you need to attempt to get the value in order to actually see that it exists. eg:

     const allowValue = response.headers.get('allow');
  2. To allow your client-side JavaScript to access this header, you need to set a response header (server-side, of course). The following line shows the header and the value that needs to be set:

     Access-Control-Expose-Headers: allow

You can read more about this on MDN: Access-Control-Expose-Headers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM