如何在不使用HttpIntercepter的情况下获取Angular中的自定义响应头

时间:2019-12-30 05:39:26

标签: angular spring-boot angular-httpclient

我在我的Angular项目中没有使用HttpIntercepter,因此如果出现错误,我想检索一些自定义的响应头。我在POST API调用中尝试过{ observe: 'response' }

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));
}

但是我只收到4个标题:

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

返回

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

但是,不返回带有前缀x-的自定义响应头。是否有任何配置可检索自定义响应头?

enter image description here

1 个答案:

答案 0 :(得分:0)

在发送响应时,您可能没有公开此标头。您的服务器需要发送Access-Control-Expose-Headers标头,以便您的自定义标头向客户端公开。

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

在春季启动响应中,

@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);

}