Using Angular's new HttpClient, how can I get all the headers when subscribing to events?

I use Angular 4.3.2 and the new HttpClient to download the file sent as a stream, and I need to get the headers (in particular Content-Disposition), but they don't seem to be present in the answer, although I see that the headers are correct sent with a request in Chrome dev tools.

This is the code:

downloadDocument(documentId: number) { const downloadDocumentUrl = `${ this.config.apiUrls.documents }/${ documentId }`; const downloadRequest = new HttpRequest('GET', downloadDocumentUrl, { reportProgress: true, responseType: 'blob' }); let percentageDownloaded = 0; this.http.request(downloadRequest).subscribe( (event: HttpEvent < any > ) => { if (event) { switch (event.type) { case HttpEventType.ResponseHeader: const contentDispositionHeader = event.headers.get('Content-Disposition'); console.log(contentDispositionHeader); // Always null here although I expected it to be there. break; case HttpEventType.DownloadProgress: if (event.total) { percentageDownloaded = Math.round((event.loaded / event.total) * 100); } break; case HttpEventType.Response: const downloadedFile: Blob = event.body; fileSaverSaveAs(downloadedFile, `${ documentId }.pdf`, true); // This is where I'd like to use content-disposition to use the actual file name. break; } } , (err) => {} ); } 

When this code is called, Chrome reports on the developer network tab provide the following response headers:

Access-Control-Allow-Credentials: True
Access-Control-Allow-Origin: http: // localhost: 4200
Content-Disposition: attachment; file name = doc5619362.pdf; File Name * = UTF-8''doc5619362.pdf
Content-Length: 88379
Content-Type: Application / PDF
Date: Thu, 03 Aug. 2017 09:43:41 GMT

Server: kestrel
Vary: Origin
X-Powered-By: ASP.NET

Any ideas on how I can access all the headers present in the answer? This is not just Content-Disposition, which is not there, all other headers are missing, except for Content-Type.

Thanks!

UPDATE

Here is a working Plunker demonstrating the problem: https://plnkr.co/edit/UXZuhWYKHrqZCZkUapgC?p=preview

+3
source share
1 answer

The problem is not Angular, it is an acknowledgment: CORS: If the server does not explicitly allow your code to read the headers, the browser hides them from it. The server should add the Access-Control-Expose-Headers:<header_name>,<header-name2> in its responses so that you can read them, but currently it allows you to make a request and read the response body by adding Access-Control-Allow-Origin

+5
source

Source: https://habr.com/ru/post/1273173/


All Articles