3

I'm not using HttpIntercepter in my Angular project and I want to retrieve some custom Response Headers in case of error. I tried { observe: 'response' } in my POST API call:

post(url, data = ''): Observable<any> {
  url = this.baseApiUrl + url;
  const headers = this.createHttpHeaders();
  const body = JSON.stringify(data);
  return this.http.post(url, body, {headers: headers, observe: 'response'}).pipe(catchError(HttpClientHelper.handleError));
}

but I'm receiving only 4 headers:

error.headers.keys().map( (key) => console.log(key + ':' + error.headers.get(key)));

returns

cache-control: no-cache, no-store, max-age=0, must-revalidate content-length: 0 expires: 0 pragma: no-cache

But, custom response headers with prefix x- are not returned. Is there any configuration to retrive custom response headers?

enter image description here

Plochie
  • 3,944
  • 1
  • 17
  • 33
Gourav Pokharkar
  • 1,568
  • 1
  • 11
  • 33

1 Answers1

5

You might have not exposed this header while sending response. Your server needs to send Access-Control-Expose-Headers header, so that your custom header is exposed to client.

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

In spring boot response,

@GetMapping("/endpoint")
public ResponseEntity<Object> someEndpoint() {

    HttpHeaders headers = new HttpHeaders();
    headers.add("x-some-header", "some_header_value");
    headers.add("Access-Control-Expose-Headers", "x-some-header"); // set this to expose custom header
    return ResponseEntity.ok()
               .headers(headers)
               .body(responseBody);

}
Plochie
  • 3,944
  • 1
  • 17
  • 33