Skip to content

Commit

Permalink
fix(AjaxObservable): ignore content-type for formdata (#1746)
Browse files Browse the repository at this point in the history
allow undefined content-type header if body is formdata

references GitHub issue #1729
  • Loading branch information
jachenry authored and benlesh committed Jun 27, 2016
1 parent 57d64cb commit 43d05e7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
4 changes: 3 additions & 1 deletion spec/observables/dom/ajax-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,9 @@ describe('Observable.ajax', () => {

expect(MockXMLHttpRequest.mostRecent.url).to.equal('/flibbertyJibbet');
expect(MockXMLHttpRequest.mostRecent.data).to.deep.equal(body);
expect(MockXMLHttpRequest.mostRecent.requestHeaders).to.deep.equal({
'X-Requested-With': 'XMLHttpRequest',
});
});

it('should not fail when FormData is undefined', () => {
Expand Down Expand Up @@ -552,4 +555,3 @@ describe('Observable.ajax', () => {
});
});
});

14 changes: 9 additions & 5 deletions src/observable/dom/AjaxObservable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class AjaxSubscriber<T> extends Subscriber<Event> {
}

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

Expand Down Expand Up @@ -271,23 +271,27 @@ export class AjaxSubscriber<T> extends Subscriber<Event> {
}
}

private serializeBody(body: any, contentType: string) {
private serializeBody(body: any, contentType?: string) {
if (!body || typeof body === 'string') {
return body;
} else if (root.FormData && body instanceof root.FormData) {
return body;
}

const splitIndex = contentType.indexOf(';');
if (splitIndex !== -1) {
contentType = contentType.substring(0, splitIndex);
if (contentType) {
const splitIndex = contentType.indexOf(';');
if (splitIndex !== -1) {
contentType = contentType.substring(0, splitIndex);
}
}

switch (contentType) {
case 'application/x-www-form-urlencoded':
return Object.keys(body).map(key => `${encodeURI(key)}=${encodeURI(body[key])}`).join('&');
case 'application/json':
return JSON.stringify(body);
default:
return body;
}
}

Expand Down

0 comments on commit 43d05e7

Please sign in to comment.