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

看来Angular会自动选择我尝试发布的数据类型,并自动创建适当的标头(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"
}

最佳答案

您的问题在这里:

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)

关于javascript - Angular HttpClient不包含指定的 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50219829/

10-16 18:29