簡體   English   中英

Angular HttpClient不包含指定的標頭

[英]Angular HttpClient is not including specified headers

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM