Skip to content

Commit

Permalink
fix(ajax): Fix case-insensitive headers in HTTP request (#4453)
Browse files Browse the repository at this point in the history
In RFC 7230 and RFC 7540 is written, that HTTP headers is case-insensitive, so this is fix for correct serializing request body base on HTTP headers.
  • Loading branch information
DostalTomas authored and benlesh committed Jan 22, 2019
1 parent be4f419 commit 673bf47
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
20 changes: 20 additions & 0 deletions spec/observables/dom/ajax-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,26 @@ describe('ajax', () => {
expect(MockXMLHttpRequest.mostRecent.data).to.equal('{"🌟":"🚀"}');
});

it('should send json body not mattered on case-sensitivity of HTTP headers', () => {
const body = {
hello: 'world'
};

const requestObj = {
url: '/flibbertyJibbet',
method: '',
body: body,
headers: {
'cOnTeNt-TyPe': 'application/json; charset=UTF-8'
}
};

ajax(requestObj).subscribe();

expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet');
expect(MockXMLHttpRequest.mostRecent.data).to.equal('{"hello":"world"}');
});

it('should error if send request throws', (done: MochaDone) => {
const expected = new Error('xhr send failure');

Expand Down
17 changes: 14 additions & 3 deletions src/internal/observable/dom/AjaxObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,17 +202,18 @@ export class AjaxSubscriber<T> extends Subscriber<Event> {
const headers = request.headers = request.headers || {};

// force CORS if requested
if (!request.crossDomain && !headers['X-Requested-With']) {
if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) {
headers['X-Requested-With'] = 'XMLHttpRequest';
}

// ensure content type is set
if (!('Content-Type' in headers) && !(root.FormData && request.body instanceof root.FormData) && typeof request.body !== 'undefined') {
let contentTypeHeader = this.getHeader(headers, 'Content-Type');
if (!contentTypeHeader && !(root.FormData && request.body instanceof root.FormData) && typeof request.body !== 'undefined') {
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}

// properly serialize body
request.body = this.serializeBody(request.body, request.headers['Content-Type']);
request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type'));

this.send();
}
Expand Down Expand Up @@ -315,6 +316,16 @@ export class AjaxSubscriber<T> extends Subscriber<Event> {
}
}

private getHeader(headers: {}, headerName: string): any {
for (let key in headers) {
if (key.toLowerCase() === headerName.toLowerCase()) {
return headers[key];
}
}

return undefined;
}

private setupEvents(xhr: XMLHttpRequest, request: AjaxRequest) {
const progressSubscriber = request.progressSubscriber;

Expand Down

0 comments on commit 673bf47

Please sign in to comment.