3

How can I set headers of a http client POST request in order to send both a bearer token and a response Type of type blob?

My current code is this:

public saveBook(format: string, req: Book) {

    var mediaType = 'application/pdf';

    this.http.post(this.ApiUrl + '/PDFBook', req, { responseType: "blob" }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'Book.' + format.toLowerCase());
        });
}

And I need to append to the current header this bearer:

let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

How can I do that?


EDIT:

I've tried doing this:

let headers = new HttpHeaders().set('responseType', 'blob')
            .set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

But I get a parsing error because it isn't able to find 'responseType'

5 Answers 5

3

You need to import ResponseContentType in the first place:

import { ResponseContentType } from "@angular/http";

Then you create your header object as you did in the example:

let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));

After that, you might put both the headers and the indication that a Blob is going to be the response type in the code as below:

public saveBook(format: string, req: Book) {

var mediaType = 'application/pdf';

this.http.post(this.ApiUrl + '/PDFBook', req, {headers: this.headers, responseType: ResponseContentType.Blob}).subscribe(
    (response) => {
        var blob = new Blob([response], { type: mediaType });
        saveAs(blob, 'Book.' + format.toLowerCase());
    });
}

I'm not sure if you also need to indicate the Blob's Content Type as a header, in which case you have to add them to the headers var (p.e: application/pdf):

    this.headers.set('Accept','application/pdf');
    this.headers.set('Content-Type','application/pdf');
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, it's not working for me... HttpClient's HttpHeaders does not accept this: {headers: this.headers, responseType: ResponseContentType.Blob}
3

I've made it. I just had to set headers just for the token first, then to concatenate them like this { headers, responseType:'blob' }

The result is actually this:

public saveBook(format: string, req: Book) {
     let headers = new HttpHeaders().set('Authorization', 'Bearer ' + localStorage.getItem('session_token'));
    var mediaType = 'application/pdf';

    this.http.post(this.ApiUrl + '/PDFBook', req, { headers, responseType:'blob' }).subscribe(
        (response) => {
            var blob = new Blob([response], { type: mediaType });
            saveAs(blob, 'Book.' + format.toLowerCase());
        });
}

Comments

1

Try this:

options = new RequestOptions();
options.headers = new Headers();
options.headers.append('Authorization', bearerToken);
options.headers.append('responseType', 'blob')

this.http.post(this.ApiUrl + '/PDFBook', req, options)

For HttpClient:

Haven't myself worked on it, you may try something like:

{headers: this.headers, responseType: ResponseContentType.Blob as 'blob'}

even if this does not work, try:

{headers: this.headers, responseType: 'blob' as 'json'}

looks weird, saw this discussion.

4 Comments

Since .append is an Http method and in HttpClient I can't append headers, should I try the following instead? Or is it somehow different? let headers = new HttpHeaders().set('responseType', 'blob') .set('Authorization', 'Bearer ' + localStorage.getItem('auth_token')); this.http.post(this.ApiUrl + '/PDFBook', req, options)
I will look into that in a while, leaving now. Just a quick comment, if your technique will work, then it should rather be something like: (new HttpHeaders()).set(...) . Please add a paranthesis when using a new object directly
Okay, no, my technique is not working and I can't test yours because I'm using HttpClient and not Http (looks like RequestOptions mangement is changed between http and httpclient). Request is sent but it don't download the pdf file. It looks like an issue with "responseType"=blob
I have added some more stuff in my answer, please give it a try.
1

responseType is not a header, please see: XMLHttpRequest.responseType

Your headers should be:

headers: HttpHeaders = new HttpHeaders ({
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + token
});

and in HttpClient

return new HttpClient.post(url, { responseType: 'blob', headers });

Comments

0

To send Bearer token and response type in header of a request try below given example

let data = JSON.stringify({
  key1: 'value1',
  key2: 'value2',
});

return this.httpclient.post(
  'https://your-url',
  data,
  // Send Bearer token and response type in same object
  { 
    headers: new HttpHeaders().set('Authorization', `Bearer ${token}`),
    responseType: 'blob'
  }
);

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.