【问题标题】:Unable to remove content-type header angular8无法删除内容类型标题 angular8
【发布时间】:2019-08-09 21:15:00
【问题描述】:

我是 Angular 8 的新手,我正在尝试将带有一些 json 数据的文件发布到休息服务。由于如果请求标头中有可用的内容类型标头,我的服务将不会接受多部分表单数据请求。我试图删除标头,但令我惊讶的是,我在请求标头中看到了内容类型标头和值。

我的代码

addProd(formData: FormData): Observable<any> {
let headers = new HttpHeaders();
headers = headers.delete("content-type");
//delete headers['content-type'];
//headers.set('content-type',undefined);
const req = new HttpRequest('POST', apiUrl + "product", formData,{
  headers:headers
});
return this.http.request(req).pipe(
  tap(_ => this.log("added product")),
  catchError(this.handleError("add product"))
);}

我的表单数据

const formData: FormData = new FormData();
formData.append('file', this.fileData, this.fileData.name);
formData.append('product', JSON.stringify(productData));

来自 Mozilla 浏览器的请求标头

我尝试将值设置为undefined,但在控制台values are undefined 中出现异常。

谁能帮助我如何在请求中发布没有内容类型标头的数据。

【问题讨论】:

  • 可能会稍后插入标题。尝试在拦截器中删除它。
  • 感谢@jpavel 的回复,但我不知道如何添加拦截器,您能帮我解决这个问题吗
  • 我会尝试详细说明答案。

标签: angular


【解决方案1】:

您可以尝试在拦截器中删除所需的标头(如果可能 - 有些标头无法删除)。

1 - 构建一个实现HttpInterceptor 接口的服务

@Injectable()
export class RemoveHeaderInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    // Get the headers without content-type
    const {'content-type', others } = req.headers;

    // As the request is immutable, clone the original
    // with the new headers
    const newReq = req.clone({
      headers: others
    });

    // dispatch the new request with the new headers
    // without content-type
    return next.handle(newReq);
  }
}

2 - 完成此操作后,您需要在根模块(可能是AppModule)上为服务提供特殊令牌(HTTP_INTERCEPTORS):

@NgModule({
  ...
  providers: [
    ...
    { 
      provide: HTTP_INTERCEPTORS, 
      useClass: RemoveHeaderInterceptor, 
      multi: true 
    },
    ...
  ],
  ..
})
export class AppModule {}

【讨论】:

  • 感谢@jpavel 的帮助。我刚刚发现我的应用程序已经有其他拦截器默认附加内容类型。我只是根据我的需要更新了它。感谢您,我能够快速调试(拦截器的想法)
猜你喜欢
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多