caitlin
caitlin

Reputation: 2819

Angular HttpClient is not including specified headers

I'm uploading a file using Angular (5)'s HttpClient as multipart form data and am running into issues with specifying headers. I am able to successfully upload the file, but I am not able to specify custom headers.

It seems like Angular is automatically picking up on the kind of data I am trying to POST and is automatically creating the appropriate headers (multipart/form-data, et cetera) but in the process is wiping out the headers I specify.

Does anyone have any idea what could be going on here?

Example code:

const formData = new FormData();
// File gets read by a FileReader, etc etc. 
// Important thing is that we're adding it to a multipart form

const imgBlob = new Blob([reader.result], { type: file.type });
formData.append('file', imgBlob, file.name);


let reqOpts = {
    params: new HttpParams(),
    headers: new HttpHeaders()
};

reqOpts.headers.append('Authorization', "Bearer YaddaYaddaYadda");

let url = this.api.url + "/media/add";

// Return the API request observable
this.http.post<boolean>(url, formData, reqOpts).subscribe(res => {

}, err => {

})

On the server side, I can call PHP's getallheaders() and I get the following result:

{
    "Host": "dev.example.com",
    "Content-Type": "multipart\/form-data; boundary=----WebKitFormBoundaryrIDpbJCAcL63ueAA",
    "Origin": "http:\/\/ip-address-goes-here:8101",
    "Accept-Encoding": "br, gzip, deflate",
    "Connection": "keep-alive",
    "Accept": "application\/json, text\/plain, *\/*",
    "User-Agent": "Mozilla\/5.0 (iPhone; CPU iPhone OS 11_2_6 like Mac OS X) AppleWebKit\/604.5.6 (KHTML, like Gecko) Mobile\/15D100",
    "Referer": "http:\/\/referer-ip-address-goes-here:8101\/",
    "Content-Length": "1055172",
    "Accept-Language": "en-us"
}

Upvotes: 0

Views: 70

Answers (1)

Mike Tung
Mike Tung

Reputation: 4821

Your issue is here:

let reqOpts = {
    params: new HttpParams(),
    headers: new HttpHeaders()
};

In order to actually set and grow out your params you need to use .set() and assign.

let params = new HttpParams().set('foo', foo).set('bar', bar);
let headers = new HttpHeaders().set(blah blah)

Upvotes: 1

Related Questions