Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular5 Response Header (Content-Disposition) Reading

Tags:

angular-http

How Can I read Response Header (Content-Disposition)? Please share resolution.

When I check at either Postman or Google Chrome Network tab, I can see 'Content-Disposition' at the response headers section for the HTTP call, but NOT able to read the header parameter at Angular Code.

// Node - Server JS
app.get('/download', function (req, res) {
  var file = __dirname + '/db.json';
  res.set({
    'Content-Type': 'text/plain',
    'Content-Disposition': 'attachment; filename=' + req.body.filename
  })
  res.download(file); // Set disposition and send it.
});


// Angular5 Code
 saveFile() {
    const headers = new Headers();
    headers.append('Accept', 'text/plain');
    this.http.get('http://localhost:8090/download', { headers: headers })
      .subscribe(
        (response => this.saveToFileSystem(response))
      );
  }

  private saveToFileSystem(response) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition'); // <== Getting error here, Not able to read Response Headers
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    const blob = new Blob([response._body], { type: 'text/plain' });
    saveAs(blob, filename);
  }
like image 417
Bhupal Avatar asked Oct 14 '25 20:10

Bhupal


2 Answers

I have found the solution to this issue. As per Access-Control-Expose-Headers, only default headers would be exposed.

In order to expose 'Content-Disposition', we need to set 'Access-Control-Expose-Headers' header property to either '*' (allow all) or 'Content-Disposition'.

// Node - Server JS
app.get('/download', function (req, res) {
var file = __dirname + '/db.json';
res.set({
  'Content-Type': 'text/plain',
  'Content-Disposition': 'attachment; filename=' + req.body.filename,
  'Access-Control-Expose-Headers': 'Content-Disposition' // <== ** Solution **
})
res.download(file); // Set disposition and send it.
});
like image 156
Bhupal Avatar answered Oct 17 '25 11:10

Bhupal


It is not the problem with Angular, is the problem with CORS.

If the server does not explicitly allow your code to read the headers, the browser don't allow to read them. In the server you must add Access-Control-Expose-Headers in the response.

In the response it will be like Access-Control-Expose-Headers:<header_name>,

In asp.net core it can be added while setting up CORS in ConfigureServices method in startup.cs

enter image description here

like image 38
Bibin Gangadharan Avatar answered Oct 17 '25 10:10

Bibin Gangadharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!