Angular HttpClient 不包括指定的 headers

Angular HttpClient is not including specified headers

我正在使用 Angular (5) 的 HttpClient 上传文件作为多部分表单数据,运行 遇到指定 headers。我可以成功上传文件,但无法指定自定义 headers.

似乎 Angular 正在自动获取我正在尝试 POST 的数据类型,并自动创建适当的 headers(multipart/form-data,等等等等),但在此过程中正在清除我指定的 headers。

有人知道这里会发生什么吗?

示例代码:

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 => {

})

在服务器端,我可以调用 PHP 的 getallheaders() 并得到以下结果:

{
    "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"
}

您的问题在这里:

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

为了实际设置和扩展您的参数,您需要使用 .set() 并分配。

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