【问题标题】:Angular HttpClient is not including specified headersAngular HttpClient 不包括指定的标头
【发布时间】:2018-05-07 17:49:17
【问题描述】:

我正在使用 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"
}

【问题讨论】:

  • 头部是不可变的,所以append返回一个新的实例,你需要分配它

标签: javascript angular angular-httpclient


【解决方案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)

【讨论】:

  • 做到了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2018-05-09
  • 2020-04-20
  • 2018-02-04
  • 1970-01-01
相关资源
最近更新 更多