Angular HttpClient不包括指定的标头

时间:2018-05-07 17:49:17

标签: javascript angular angular-httpclient

我使用Angular(5)的 HttpClient 上传文件作为多部分表单数据,并且遇到了指定标题的问题。我能够成功上传文件,但我无法指定自定义标题。

似乎Angular会自动获取我尝试POST的数据类型,并自动创建相应的标头(multipart/form-data等等),但在此过程中会消除我指定的标头。

有谁知道这里会发生什么?

示例代码:

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

1 个答案:

答案 0 :(得分:1)

您的问题在这里:

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)