javascript - Angular HttpClient 不包括指定的标头
问题描述
我正在使用 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)
推荐阅读
- laravel - Laravel 中的 firstOrFail() 函数行为
- javascript - 无法获取使用 ng-packagr 发布的已发布包
- unity3d - Unity 中封装协程的奇怪问题
- android - 导航架构组件 - 带有 CollapsingToolbar 的详细视图
- reactjs - react - 具有 n 列的反应表
- c - NULL 与 C 中的 0 有何不同?
- javascript - 如何在对象上定义函数并仍然能够运行它来设置初始对象属性
- mysql - 插入错误 - 数据不会插入
- awk - awk:打印与文件中的模式不匹配的行,查看特定列
- jsf - 页面刷新时未调用 JSF init