如何告诉 Angular 2 自动停止设置 Content-Type 标头?

yog*_*mbi 6 javascript json content-type laravel angular

我目前正在尝试使用 Angular 2(通过 Ionic 2)应用程序访问 API。我们的 Laravel 后端的设置方式是,它需要一个带有请求内容类型的 Accept 标头,而不是 Content-Type 标头。不仅仅是一个空的 Content-Type 标头,而且根本没有。

因此,我在 Http 中设置必要的参数,省略标头中的 Content-Type,这就是问题开始的地方:Angular 2 显然无法摆脱 Content-Type。如果我给它一个对象作为请求的正文,它会将 Content-Type 设置为 application/json。这仍然是可以理解的。然后我对对象进行字符串化,这会导致 Angular 将 Content-Type 设置为 text/plain。尝试,通过

headers = new Header({Accept: 'application/json', Content-Type: undefined});
Run Code Online (Sandbox Code Playgroud)

或者

headers.append("Content-Type", undefined);
Run Code Online (Sandbox Code Playgroud)

或者我能想象到的任何标头的任何其他组合,其中包含 application/json 的 Accept 而没有其他任何内容,即使 headers.set 或 headers.delete 失败,Angular 2 也会继续做它的事情。

其他地方建议将 Content-Type 设置为 undefined,我也尝试将其设置为空字符串,在传递字符串化 JSON 时将其设置为 application/json,Angular 只是不关心我想要什么。有没有办法关闭这种自动性?我是否仍然做错了什么(我正在导入标头,这又名缺乏标头,这是其他地方的问题,所以应该排除)?

代码如下:

import { Injectable, Inject } from '@angular/core';

import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { ConfsService } from '../confs/confs.service';

import { ApiRequestBody }   from './api.request.body';

@Injectable()
export class ApiService {
    constructor(public confs: ConfsService, private apiRequestBody: ApiRequestBody, private http: Http) {

    post (method: string, data: any):Promise<any> {
        const api = this.confs.get().api;
        const url = api['server'] + "" + api[method];
        let allParams = this.apiRequestBody.toJSON(data);
        let body = JSON.stringify(allParams);
        let headers = new Headers({
            'Accept': 'application/json',
            'Content-Type': undefined,
        });
        let options = new RequestOptions({ headers: headers });     
        let obj = this.http.post(url, body, options).toPromise();
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)

ConfsService 仅获取几个配置参数,即 api 服务器 URL,而 ApiRequestBody 获取一个服务,该服务创建一组标准参数,API 甚至需要查看请求(除了通过数据传入的参数)参数(然后合并到 toJSON 方法中的标准参数中)- 没有什么火箭科学。我正在执行 toPromise() ,因为我发现在这种特殊情况下的承诺更容易处理。

mer*_*ech 4

在深入研究 Angular 源代码后,我得出的结论是这是不可能的。请参阅 static_request.ts ( https://github.com/angular/angular/blob/5293794316cc1b0f57d5d88b3fefdf6ae29d0d97/packages/http/src/static_request.ts ),它会首先检查您是否已手动将标头设置为特定字符串,并且未定义或者空字符串将传递到 detectorContentTypeFromBody 函数,如果您的请求正文为 null,该函数将仅设置 ContentType.NONE。

  /**
   * Returns the content type enum based on header options.
   */
  detectContentType(): ContentType {
    switch (this.headers.get('content-type')) {
      case 'application/json':
        return ContentType.JSON;
      case 'application/x-www-form-urlencoded':
        return ContentType.FORM;
      case 'multipart/form-data':
        return ContentType.FORM_DATA;
      case 'text/plain':
      case 'text/html':
        return ContentType.TEXT;
      case 'application/octet-stream':
        return this._body instanceof ArrayBuffer ? ContentType.ARRAY_BUFFER : ContentType.BLOB;
      default:
        return this.detectContentTypeFromBody();
    }
  }

  /**
   * Returns the content type of request's body based on its type.
   */
  detectContentTypeFromBody(): ContentType {
    if (this._body == null) {
      return ContentType.NONE;
    } else if (this._body instanceof URLSearchParams) {
      return ContentType.FORM;
    } else if (this._body instanceof FormData) {
      return ContentType.FORM_DATA;
    } else if (this._body instanceof Blob) {
      return ContentType.BLOB;
    } else if (this._body instanceof ArrayBuffer) {
      return ContentType.ARRAY_BUFFER;
    } else if (this._body && typeof this._body === 'object') {
      return ContentType.JSON;
    } else {
      return ContentType.TEXT;
    }
  }
Run Code Online (Sandbox Code Playgroud)

更新:

看起来实际上可以通过扩展 Request 并重载 detectorContentType 函数以返回 0 来实现。但这需要访问非公共代码,因此将来可能会中断:

import {Http, Headers, RequestOptions, RequestMethod, Request, BaseRequestOptions, Response} from '@angular/http';
import { ContentType } from '@angular/http/src/enums';
import { RequestArgs } from '@angular/http/src/interfaces';

class NoContentRequest extends Request {
  constructor(args: RequestArgs) {
    super(args);
  }
  detectContentType(): ContentType {
    return 0;
  }
}

const headers = new Headers({Accept: 'application/json'});

const request  = new NoContentRequest({
  method: RequestMethod.Post,
  url: 'https://www.example.com/example',
  responseType: ResponseContentType.Json,
  headers: headers,
  body: body
});

this._http.request(request)
  .catch((error: Response | any) => { console.error(error); return Observable.throw(error); })
  .first()
  .subscribe();
Run Code Online (Sandbox Code Playgroud)