【问题标题】:How to get custom response headers in Angular without use of HttpIntercepter如何在不使用 HttpIntercepter 的情况下在 Angular 中获取自定义响应标头
【发布时间】:2020-04-18 22:11:51
【问题描述】:

我没有在我的 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) =&gt; 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- 的自定义响应标头。是否有任何配置可以检索自定义响应标头?

【问题讨论】:

  • 检查 chrome 检查网络选项卡,对于这个请求,你真的得到了标题。如果可能,还可以从网络选项卡添加屏幕截图。
  • 是的。我在 Network 面板的 Headers 选项卡中收到这些标题。
  • 添加截图。
  • 什么是后端服务器? (spring-boot、.net 等)?
  • 我们在后端使用 spring-boot。

标签: angular spring-boot angular-httpclient


【解决方案1】:

您在发送响应时可能没有公开此标头。您的服务器需要发送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);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2017-12-10
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2013-08-27
    • 2017-02-26
    相关资源
    最近更新 更多