首页 > 解决方案 > Angular HTTPClient 忽略标头

问题描述

由于某种原因,发出请求时我的标头被忽略了。

(以下是我正在做的精简版)

let headers = new Headers();

headers = headers.set('Content-Type', file.mime);
headers = headers.set('X-Blah', "Test");

return this.httpClient.put<HttpEvent<Blob>>(`${encodeURIComponent(file.name)}`, {
   data: file,
   responseType: "blob",
   observe: "events",
   headers: headers,
   withCredentials: this.configuration.withCredentials
});

我在使用开发工具时注意到的是 [ HTTPHeaders]headers对象只是将新标头放入lazyUpdate属性/映射中。

当前有一个 HTTPInterceptor,当它触发时,请求对象不包含我在请求中设置的任何标头。

它被一遍又一遍地检查,请求的一切都是正确的,标头在对象中(尽管在那个lazyUpdate映射中),但是由于某些未知的原因,它们似乎在请求中被忽略了。因此,请求将其Content-Type属性覆盖,因为它认为那里没有。

有什么想法吗?

标签: angularangular-httpclientangular-http-interceptors

解决方案


似乎我一直在处理的文档是错误的。它与this.httpClient.put(url, body, options)方法有关....似乎我正在努力理解该body参数是可选的,但事实并非如此。

所以最后一次调用应该将 Blob 作为第二个参数传递,并将选项保留为第三个参数......

return this.httpClient.put<HttpEvent<Blob>>(`${encodeURIComponent(file.name)}`, file, {
   responseType: "blob",
   observe: "events",
   headers: headers,
   withCredentials: this.configuration.withCredentials
});

推荐阅读