Problem with retrieving headers in angular 6?

别等时光非礼了梦想. 提交于 2019-12-31 03:58:06

问题


Here is my service

executeProcess(): Observable<any> {
    return this._httpClient.post(this.baseUrl + '/api/survey/process/execute', {}, { observe: 'response', responseType: 'text' as 'text' });
}

And in my component I am calling it like this

this._httpService.executeProcess().subscribe(res => {
      console.log(res);
}

And this is my res.headers

{
  "normalizedNames": {},
  "lazyUpdate": null,
  "headers": {}
}

which has a headers object which is empty. In the backend of this api, I am sending a header called location which is being shown in the network tab of Chrome. Everything is working through chrome's network tab, but in angular, I am unable to retrieve this header.


回答1:


Have you tried reading the full response?

HttpClient reading the full response

showConfigResponse() {
  this.configService.getConfigResponse()
    // resp is of type `HttpResponse<Config>`
    .subscribe(resp => {
      // display its headers
      const keys = resp.headers.keys();
      this.headers = keys.map(key =>
        `${key}: ${resp.headers.get(key)}`);

      // access the body directly, which is typed as `Config`.
      this.config = { ... resp.body };
    });
}

EDIT:

Also try to expose your location header with Access-Control-Expose-Headers on your backend. See this link for reference: Using CORS

Access-Control-Expose-Headers (optional) - The XMLHttpRequest 2 object has a getResponseHeader() method that returns the value of a particular response header. During a CORS request, the getResponseHeader() method can only access simple response headers. Simple response headers are defined as follows:

Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma

If you want clients to be able to access other headers, you have to use the Access-Control-Expose-Headers header. The value of this header is a comma-delimited list of response headers you want to expose to the client.



来源:https://stackoverflow.com/questions/53309992/problem-with-retrieving-headers-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!