Angular $ http的transformRequest不会更改标题

时间:2016-08-31 13:05:23

标签: javascript angularjs typescript http-headers karma-jasmine

美好的一天!

我已创建了RequestTransformer服务,以便更改内容类型标头并序列化发布数据。

这是我用来更改标头并将数据序列化委托给serializeData方法的方法(serializeData工作正常)。

class RequestTransformer implements IRequestTransformer {

  public transformAsFormPost(data, getHeaders:IHttpHeadersGetter): string {
    let headers = getHeaders();
    headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    return  RequestTransformer.serializeData(data) ;
  }
  /*Other code logic */
}

我也创建了测试用例:

describe('Test RequestTransformerService functionality', function () {
    let $httpBackend: IHttpBackendService;
    let $http: IHttpService;

    beforeEach(inject(function (_$httpBackend_, _$http_) {
      $httpBackend = _$httpBackend_;
      $http = _$http_;
    }));

    it('should transform post data as a regular form post', function () {
      $http({
        method: "POST",
        url: 'test-transform.com',
        transformRequest: RequestTransformer.transformAsFormPost,
        data: {
          id: 4,
          name: "John",
          status: "Best Friend"
        }
      });

      $httpBackend.expectPOST('test-transform.com',
        function (data) {
          expect(data).toEqual('id=4&name=John&status=Best+Friend');
          return data;
        },
        function (headers: Array) {
          expect(headers['Content-Type']).toEqual('application/x-www-form-urlencoded; charset=utf-8');
          return headers;
        }).respond(201, '');

      $httpBackend.flush();
    })
  });

测试运行的结果是:

  

预期' application / json; charset = utf-8'平等   '应用程序/ X WWW的窗体-urlencoded;字符集= UTF-8'

这可能是什么原因?

0 个答案:

没有答案