Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions packages/common/http/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ function isFormData(value: any): value is FormData {
return typeof FormData !== 'undefined' && value instanceof FormData;
}

/**
* Safely assert whether the given value is a URLSearchParams.
*
* In some execution environments URLSearchParams is not defined.
*/
function isURLSearchParams(value: unknown): value is URLSearchParams {
return typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams;
}

/**
* An outgoing HTTP request with an optional typed body.
*
Expand Down Expand Up @@ -247,8 +256,8 @@ export class HttpRequest<T> {
typeof this.body === 'string') {
return this.body;
}
// Check whether the body is an instance of HttpUrlEncodedParams.
if (this.body instanceof HttpParams) {
// Check whether the body is an instance of HttpUrlEncodedParams or URLSearchParams.
if (this.body instanceof HttpParams || isURLSearchParams(this.body)) {
return this.body.toString();
}
// Check whether the body is an object or array, and serialize with JSON if so.
Expand Down Expand Up @@ -289,8 +298,8 @@ export class HttpRequest<T> {
if (typeof this.body === 'string') {
return 'text/plain';
}
// `HttpUrlEncodedParams` has its own content-type.
if (this.body instanceof HttpParams) {
// `HttpUrlEncodedParams` and `URLSearchParams` have their own content-type.
if (this.body instanceof HttpParams || isURLSearchParams(this.body)) {
return 'application/x-www-form-urlencoded;charset=UTF-8';
}
// Arrays, objects, and numbers will be encoded as JSON.
Expand Down
11 changes: 11 additions & 0 deletions packages/common/http/test/request_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ const TEST_STRING = `I'm a body!`;
expect(withParams.detectContentTypeHeader())
.toEqual('application/x-www-form-urlencoded;charset=UTF-8');
});
it('serializes parameters as urlencoded', () => {
if (typeof URLSearchParams !== 'undefined') {
const params = new URLSearchParams();
params.set('first', 'test');
params.set('second', 'data');
const withParams = baseReq.clone({body: params});
expect(withParams.serializeBody()).toEqual('first=test&second=data');
expect(withParams.detectContentTypeHeader())
.toEqual('application/x-www-form-urlencoded;charset=UTF-8');
}
});
});
describe('parameter handling', () => {
const baseReq = new HttpRequest('GET', '/test', null);
Expand Down